我正在尝试使用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“的参数。”
3条答案
按热度按时间njthzxwz1#
您可能需要定义操作类型。请尝试以下操作:
jw5wzhpr2#
唯一看起来不对的是这一行:
它应该
bmvo0sr53#
我找到了答案。我必须先在我的商店里使用这个:
然后在我的组件: