React and redux tookit:当其他动作完成时,如何调度动作



每当删除成功时,我都会尝试显示一个小吃条。我为此创建了一个动作。

我在哪里发送该操作?

目前,我的代码如下:

export const deleteSelectedEntry = createAsyncThunk('entries/delete/selected', async (id: string) => {
const response = await BackendService.deleteEntry(id);
const dispatch = useAppDispatch();
dispatch(setSnackBarState({
state: true,
message: "SUCCESS DELETING"
}));
return response.data
})

这是您在使用redux工具包时创建的一个slice类中的异步thunk。

我根据redux工具包在教程中的建议为调度方法创建了一个钩子:

export const useAppDispatch: () => AppDispatch = useDispatch

但是,在我认为应该能够放置dispatch方法的任何地方,我都会得到一个错误,即我不能在那里使用react钩子。

我最初的尝试是把它放在extraReducers:

extraReducers(builder) {
builder
.addCase(deleteSelectedEntry.fulfilled, (state: MyState, action: PayloadAction<Entry>) => {
// do Stuff
})

然后如何从react redux中的其他操作中调度操作?我在StackOverflow上看到过一些例子,人们在asyncThunk中使用useDispatch方法。

感谢帮助和小费!

如有必要,我会发布更多代码。

我认为您最初的直觉是正确的,使用了extraReducers切片属性。以下是我为我所称的";notificationSlice":

import { createEntityAdapter, createSlice, isAnyOf } from '@reduxjs/toolkit'
import {
doStuffPage1
} from './page1.slice'
import {
doStuffPage2
} from './page2.slice'
const notificationsAdapter = createEntityAdapter()
const initialState = notificationsAdapter.getInitialState({
error: null,
success: null,
warning: null,
info: null,
})
const notificationsSlice = createSlice({
name: 'notifications',
initialState,
reducers: {},
extraReducers: builder => {
builder
// set success on fulfilled
.addMatcher(
isAnyOf(
doStuffPage1.fulfilled,
doStuffPage2.fulfilled,
),
(state, action) => {
state.error = null
state.warning = null
state.success = action.payload.message
}
)
// set error on rejections
.addMatcher(
isAnyOf(
doStuffPage1.rejected,
doStuffPage2.rejected,
),
(state, action) => {
state.error = action?.payload
state.warning = null
state.success = null
}
)
// reset all messages on pending
.addMatcher(
isAnyOf(
doStuffPage1.pending,
doStuffPage2.pending,
),
(state, action) => {
state.error = null
state.success = null
state.warning = null
}
)
},
})
export const {
clearNotifications,
setError,
setSuccess,
setWarning,
setInfo,
} = notificationsSlice.actions
export default notificationsSlice.reducer
export const getErrorMsg = state => state.notifications.error
export const getSuccessMsg = state => state.notifications.success
export const getInfoMsg = state => state.notifications.info
export const getWarningMsg = state => state.notifications.warning

需要注意的一些事项:

  • 选择器将被导入高级组件中的某个位置,并将使用额外的snackbar逻辑THERE
  • 您需要确保您的thunk(doStuffPage1/doStuffPage 2(正在返回带有成功/错误结果的消息

最新更新