简体   繁体   English

是否可以使用与渲染功能相同的渲染功能来访问redux存储状态<Provider />

[英]Is it possible to access redux store state in same render function as <Provider />

So what I mean here is: 所以我的意思是:

const App = () => {
  return (
    <Provider store={store}>
      <h1>{store.state.title}</h1> // For example
    </Provider>
  );
}

So in the example above I'm trying to access the title prop in state. 因此,在上面的示例中,我试图访问状态为title道具。

Yes you can use store.getState() 是的,您可以使用store.getState()

So in your case will be: 因此,您的情况将是:

const App = () => {
  const currentStore = store.getState()
  return (
    <Provider store={store}>
      <h1>{currentStore.title}</h1> // For example
    </Provider>
  );
}

This is XY problem. 这是XY问题。 In order to update <h1> with new value, <Provider> would have to be re-rendered. 为了用新值更新<h1> ,必须重新呈现<Provider> Instead, <h1>{store.state.title}</h1> should be moved to separate connected component: 相反, <h1>{store.state.title}</h1>移至单独的已连接组件:

const Title = connect(...)(({ title }) => <h1>{title}</h1>;

And used as such: 并这样使用:

<Provider store={store}>
  <Title/>
</Provider>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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