【问题标题】:React and redux-tookit: How to dispatch action when other action completed?React 和 redux-toolkit:当另一个动作完成时如何调度动作?
【发布时间】:2022-10-19 02:47:54
【问题描述】:

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

我在哪里调度该动作?

目前,我的代码如下所示:

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 工具包时创建的切片类之一中的异步 thunk。

我按照教程中 redux-toolkit 的建议为 dispatch 方法创建了一个钩子:

export const useAppDispatch: () => AppDispatch = useDispatch

但是,无论我认为我应该能够放置调度方法,我都会收到一个错误,我不能在那里使用反应钩子。

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

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

那么你如何在 react redux 中从其他动作中分派动作?我在 StackOverflow 上看到了人们在 asyncThunk 中使用 useDispatch 方法的示例。

帮助和提示表示赞赏!

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

【问题讨论】:

    标签: reactjs redux-toolkit


    【解决方案1】:

    我认为您最初的直觉是正确的,使用 extraReducers slice 属性。以下是我为所谓的“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(
              didStuffPage1.fulfilled,
              didStuffPage2.fulfilled,
            ),
            (state, action) => {
              state.error = null
              state.warning = null
              state.success = action.payload.message
            }
          )
          // set error on rejections
          .addMatcher(
            isAnyOf(
              didStuffPage1.rejected,
              didStuffPage2.rejected,
            ),
            (state, action) => {
              state.error = action?.payload
              state.warning = null
              state.success = null
            }
          )
          // reset all messages on pending
          .addMatcher(
            isAnyOf(
              didStuffPage1.pending,
              didStuffPage2.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
    

    需要注意的一些事项:

    • 选择器将被导入高级组件中的某处,并且将在该处使用额外的快餐栏逻辑
    • 您需要确保您的 thunk (doStuffPage1/doStuffPage2) 返回带有成功/错误结果的消息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      • 2017-04-18
      • 2020-04-23
      • 2021-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多