Accessing a part of reducer state from one reducer within another reducer

前端 未结 3 1885
余生分开走
余生分开走 2020-12-03 02:50

I do not know how to access a boolean isLoading flag from reducerForm.js reducer in reducerRegister.js. I have used combineReduc

相关标签:
3条回答
  • 2020-12-03 03:38

    A reducer cannot access another reducer's state, but if you're using redux-thunk you can do so from within an action creator. As an example, you can define an action creator like this:

    export const someAction = () =>
      (dispatch, getState) => {
        const someVal = getState().someReducer.someVal;
        dispatch({ type: types.SOME_ACTION, valFromOtherReducer: someVal });
      };
    
    0 讨论(0)
  • 2020-12-03 03:47

    This is covered in the Redux FAQ at https://redux.js.org/faq/reducers#how-do-i-share-state-between-two-reducers-do-i-have-to-use-combinereducers:

    Many users later want to try to share data between two reducers, but find that combineReducers does not allow them to do so. There are several approaches that can be used:

    • If a reducer needs to know data from another slice of state, the state tree shape may need to be reorganized so that a single reducer is handling more of the data.
    • You may need to write some custom functions for handling some of these actions. This may require replacing combineReducers with your own top-level reducer function. You can also use a utility such as reduce-reducers to run combineReducers to handle most actions, but also run a more specialized reducer for specific actions that cross state slices.
    • Async action creators such as redux-thunk have access to the entire state through getState(). An action creator can retrieve additional data from the state and put it in an action, so that each reducer has enough information to update its own state slice.
    0 讨论(0)
  • 2020-12-03 03:48

    React Redux works on unidirectional data flow.

    Action ---> Reducer /store ---> Reducer
    

    Reducer works on small subset of store, you can not access store inside reducer which is not part of Reducer. you can either need to fire new action from the component based on reducer state return.

    0 讨论(0)
提交回复
热议问题