[英]How do I access the state of another component via Redux store
Say I have two components, App and DialogBox;假设我有两个组件,App 和 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()
;现在,当我必须打开对话框时,我调用
dialogBoxActions.openDialog()
并且,当我关闭对话框时,我调用dialogBoxActions.closeDialog()
和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?例如,我可以使用应用商店中的 state.dialog 吗? 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. ComponentWillReceiveProps
确实获得了 checkCloseDialog object,但它获得了旧的 state。 I debugged to find out that it gets triggered correctly after the reducer function of the DialogBox component but I get old data.我调试发现它在 DialogBox 组件的减速器 function 之后被正确触发,但我得到了旧数据。
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?是否有任何优雅的方式来访问彼此的商店,或者 Redux 的理念是组件应该通过操作相互通信?
Ah, Okay.啊好吧。 my bad.
我的错。
Yes, it is possible.对的,这是可能的。 And it works.
它有效。 My mistake was I was trying to use it inside
ComponentWillReceiveProps()
method.我的错误是我试图在
ComponentWillReceiveProps()
方法中使用它。 The thing is, it seems the redux store gets updated later.问题是,redux 商店似乎稍后会更新。 So,
ComponentWillReceiveProps()
will hold an old state.因此,
ComponentWillReceiveProps()
将保存旧的 state。
Hence, render()
and ComponentDidUpdate()
methods get the updated state.因此,
render()
和ComponentDidUpdate()
方法获取更新的 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.例如,Dialog 不应该关心调用者在它自己关闭后应该做什么。 Instead the caller should subscribe to the state of Dialog to decide what to do.
相反,调用者应该订阅 Dialog 的 state 来决定要做什么。
Hope this helps others.希望这对其他人有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.