简体   繁体   中英

How do I access the state of another component via Redux store

Say I have two components, App and DialogBox;

so my react store also has two objects

const rootReducer = combineReducers({
    app: appReducer,
    dialog: dialogReducer
});

export const store = createStore(rootReducer);

Now, when I have to open the Dialog box, I call the dialogBoxActions.openDialog() And, when I close the Dialog box, I call dialogBoxActions.closeDialog() and also appActions.notifyDialogClosed() ;

This works, but is there a way to do this in more clearer way?

For example can I use the state.dialog from the store in App? This is what I tried in the App

const mapStateToProps = (state) => {
    return {
        checkCloseDialog: state.dialog.openDialog
    }
}

The ComponentWillReceiveProps does get the checkCloseDialog object, but it gets the old state. I debugged to find out that it gets triggered correctly after the reducer function of the DialogBox component but I get old data.

Is there any elegant way of accessing each other's store or is it Redux's philosophy that components should communicate with each other via actions?

Ah, Okay. my bad.

Yes, it is possible. And it works. My mistake was I was trying to use it inside ComponentWillReceiveProps() method. The thing is, it seems the redux store gets updated later. So, ComponentWillReceiveProps() will hold an old state.

Hence, render() and ComponentDidUpdate() methods get the updated state.

The aim here is to help reduce the multiple action calls between independent components.

For example, a Dialog should not be concerned with what the caller should do after it closes itself. Instead the caller should subscribe to the state of Dialog to decide what to do.

Hope this helps others.

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