简体   繁体   中英

How to handle state across different reducers for triggering notification in react redux

How do i update root state on store from one reducer to another reducer if some message notification triggers. I want to change message state of store when user login happens and wants to show that message on top level MESSAGE component. I want to change message state from userReducer on dispatching LOGIN_FAILURE action. But it is updating message in initialState.user.messages itself but i want to update in initialState.messages not in initialState.user.messages.

How can i do this?

Dispatching LOGIN_FAILURE actions.

initialState.js

在此处输入图像描述

rootReducer.js used in createStore

在此处输入图像描述

userReducer.js

在此处输入图像描述

messageReducer.js

在此处输入图像描述

App.js in which MESSAGE component is used

在此处输入图像描述

As you may know each reducer has its own state, so for example for userReducer you are using the initialState , so

const initialState = {
  user: {},
  messages: []
};

the initial state above, it's used into userReducer only, so it is namespace for user only instead of be sharing cross reducer, so whatever change you do into userReducer will affect only its state I mean user: {} , in the case that you want to update messages for messageReducer , so should move your logic for LOGIN_FAILURE to the reducer that is intended to affect, so if for example yo need to listen for LOGIN_FAILURE into userReducer too, you can do it, but this should be done only if you need to affect something related to the user state instead of message state.

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