Updating state managed by another reducer

后端 未结 2 1788
梦如初夏
梦如初夏 2021-02-01 23:01

In my React app, my appReducer manages global stuff such as notifications, user info, etc.

One of the modules in the app is the inventory module which has its own reduce

2条回答
  •  萌比男神i
    2021-02-01 23:36

    In Redux official document there's a chapter called 'Beyond combineReducers'. It mentioned about Sharing data between slice reducers.

    https://redux.js.org/recipes/structuring-reducers/beyond-combinereducers#sharing-data-between-slice-reducers

    I personally prefer the third solution mentioned in the link, which is adding a third customized reducer to handle the "special" cases where data needs to be shared across slices, then use reduce-reducers to combine the new customized reducer and the original combined reducer (i.e. appReducer + inventoryReducer).

    const crossSliceReducer = (state, action) => {
      if (action.type === 'CROSS_SLICE_ACTION') {
        // You can access both app and inventory states here
      }
      return state;
    }
    // Combine the reducers like you did before
    const combinedReducer({app: appReducer, inventory: inventoryReducer});
    
    // Add the cross-slice reducer to the root reducer
    const rootReducer = reduceReducers(combinedReducer, crossSliceReducer)
    

提交回复
热议问题