redux 无法使用dispatch()分派动作

vm0i2vca  于 2022-11-12  发布在  其他
关注(0)|答案(3)|浏览(233)

我正在尝试使用redux工具包调度一个异步操作并做出React。我的操作和切片如下所示:

export const newRegister = createAsyncThunk('users', async (user: User) => {
    const response = await AuthService.register(
        user.username,
        user.email,
        user.password
    )
    return response.data
})

const registerSlice = createSlice({
    name: 'register',
    initialState: {
        username: '',
        password: '',
        isLogin: false,
    },
    reducers: {
        register: (state, action) => {
            state.username = action.payload.username
            state.password = action.payload.password
            state.isLogin = true
        },
    },
    extraReducers: (builder) => {
        builder.addCase(newRegister.fulfilled, (state, action) => {
            state.username = action.payload.username
            state.password = action.payload.password
            state.isLogin = true
        })
    },
})

我的商店是这样的:

import { combineReducers, configureStore } from '@reduxjs/toolkit'
import { cartReducer, authReducer, registerReducer } from './slices'
import { useDispatch } from 'react-redux'
import storage from 'redux-persist/lib/storage'
import {
    persistStore,
    persistReducer,
    FLUSH,
    REHYDRATE,
    PAUSE,
    PERSIST,
    PURGE,
    REGISTER,
} from 'redux-persist'

const persistConfig = {
    key: 'root',
    storage,
}

const reducers = combineReducers({
    auth: authReducer,
    cart: cartReducer,
    register: registerReducer,
})

const persistedReducer = persistReducer(persistConfig, reducers)

export const store = configureStore({
    reducer: persistedReducer,
    middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware({
            serializableCheck: {
                ignoredActions: [
                    FLUSH,
                    REHYDRATE,
                    PAUSE,
                    PERSIST,
                    PURGE,
                    REGISTER,
                ],
            },
        }),
})

export type AppDispatch = typeof store.dispatch
export const useAppDispatch: () => AppDispatch = useDispatch

export const persistor = persistStore(store)

我尝试在register组件中使用dispatch()调用我的操作,如下所示(我使用formik进行字段检查):

const formik = useFormik({
        initialValues: {
            username: '',
            email: '',
            password: '',
        },
        validationSchema: validationSchema,
        onSubmit: () => {
            const user: User = {
                username: formik.values.username,
                email: formik.values.email,
                password: formik.values.password,
            }
            dispatch(newRegister(user))
        },
    })

问题是我的newRegister()操作一直出现以下错误:“无法将类型为”AsyncThunkAction〈any,User,{}〉“的参数赋给类型为”AnyAction“的参数。”

njthzxwz

njthzxwz1#

您可能需要定义操作类型。请尝试以下操作:

import { PayloadAction } from '@reduxjs/toolkit';

    const registerSlice = createSlice({
        name: 'register',
        initialState: {
            username: '',
            password: '',
            isLogin: false,
        },
        reducers: {
            register: (state, action:PayloadAction<string | boolean>) => {
                state.username = action.payload.username
                state.password = action.payload.password
                state.isLogin = true
            },
        },
        extraReducers: (builder) => {
            builder.addCase(newRegister.fulfilled, (state, action:PayloadAction<string | boolean>) => {
                state.username = action.payload.username
                state.password = action.payload.password
                state.isLogin = true
            })
        },
    })
jw5wzhpr

jw5wzhpr2#

唯一看起来不对的是这一行:

export const useAppDispatch: () => AppDispatch = useDispatch

它应该

export const useAppDispatch = () => useDispatch<AppDispatch>()
bmvo0sr5

bmvo0sr53#

我找到了答案。我必须先在我的商店里使用这个:

export type AppDispatch = typeof store.dispatch
export const useAppDispatch = () => useDispatch<AppDispatch>()

然后在我的组件:

const dispatch = useDispatch<AppDispatch>();

相关问题