[英]Update and Use redux state in sibling react components
I have a component called <App/>
, it is a parent component with two children inside it ie <Header/>
and <Main/>
So the things looks like this 我有一个名为
<App/>
的组件,它是一个父组件,其中有两个子组件,即<Header/>
和<Main/>
所以事情看起来像这样
<App>
<Header/>
<Main />
<App/>
When my Header component mounts I set some redux state inside componentDidMount()
Then I tried to use that state in my <Main/>
componentDidMount()
but my state is always empty in Main component however I already set that in Header component. 当安装Header组件时,我在
componentDidMount()
设置了一些redux状态,然后尝试在<Main/>
componentDidMount()
使用该状态,但是我的状态在Main组件中始终为空,但是我已经在Header组件中设置了该状态。
You are confusing component state and store state. 您正在混淆组件状态和存储状态。
You need to use react-redux
connect
or useSelector
/ useDispatch
to connect both components with your store state. 您需要使用
react-redux
connect
或useSelector
/ useDispatch
来将两个组件与您的存储状态连接起来。
Also you would need an <Provider store={store}></Provider>
to provide the store context to your components. 另外,您还需要一个
<Provider store={store}></Provider>
来为您的组件提供商店上下文。
You should really read the React Redux and Redux documentation, to get the idea. 您应该真正阅读React Redux和Redux文档,以了解它。
代替使用componentDidMount()
在< Main />
部件尝试使用componentDidUpdate()
来检查状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.