简体   繁体   中英

How to change the state of another reducer in react.js redux?

How can I change the state of MenuReducer in SideBarReducer? The meaning of this is to show a warning message in the menu when the user does an action in the sidebar. The user will in the future also do action in other reducers that will cause the warning in the MenuReducer to pop up.

MenuReducer:

import actionTypes from '../action-types';

export const initialState = {
  showWarning: false,
};

export default function MenuReducer(state = initialState, action) {
  switch (action.type) {
    case actionTypes.REQUEST_REFRESH:
      if (action.payload.unsavedChanges) {
        return { ...state, showWarning: true };
      }
    default:
      return state;
  }
}

SidebarReducer:

import actionTypes from '../action-types';

export default function sideBarReducer(state = initialState, action) {
  switch (action.type) {
    case actionTypes.REQUEST_CLOSE:
      if (action.payload.unsavedChanges) {
        // Change the state of MenuReducer
      }
    default:
      return state;
  }
}

You can create an action that dispatches 2 actions (using Thunk middleware). You can also catch the same action in both reducers and update stuff accordingly.

you should not fire action from another reducer, that's anti-pattern. All action need to fire in React component lifecycle or in action creator.

Reducer is only meant for the state change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM