【问题标题】:Should I use Redux store.subscribe() or wrap my app with react-redux <Provider>?我应该使用 Redux store.subscribe() 还是使用 react-redux <Provider> 包装我的应用程序?
【发布时间】:2019-05-03 23:27:09
【问题描述】:

我见过两种方法: this example,摘自 Dan Abramov 的课程, 他正在使用这种方法:

const render = () => {
  ReactDOM.render(
    <Counter
      value={store.getState()}
      onIncrement={() =>
        store.dispatch({
          type: 'INCREMENT'           
        })            
      }
      onDecrement={() =>
        store.dispatch({
          type: 'DECREMENT'           
        })            
      }
    />,
    document.getElementById('root')
  );
};

store.subscribe(render);

Redux 中的 store.subscribe() 函数允许添加侦听器,这些侦听器会在调度操作时被调用。

在这个 other example 中,这是 Redux 文档中的一个示例:

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

不使用 store.subscribe,而是将整个 App 包装在 &lt;Provider&gt; 组件中。

这两种方法有什么区别? 似乎他们在做同样的事情,那就是确保 App 拥有最新版本的状态。

如果我使用 &lt;Provider&gt; 包装了我的应用程序,我可以/应该使用 Store.subscribe 吗?

【问题讨论】:

    标签: reactjs redux redux-store


    【解决方案1】:

    您可能可以使用第一种方法,但是以后您应该将所有其他组件都传递给商店。手动执行此操作需要大量工作,但除此之外,它会使事情变得困难,例如测试等。

    Provider 不是Redux 的一部分,但带有react-redux 以使事情变得更容易。你用它包装你的组件,它会一直向下传递存储。 react-redux 还提供了connect 函数。您可以在组件中使用它来访问您的操作调度程序和您的状态。

    因此,您可以很容易地看到使用Provider 组件几乎是事实上的标准。因此,您可能想使用它,而不必费心手动执行store.subscribe 并将您的商店传递给其他组件。所以,如果你使用Provider,你就不会使用store.subscribe

    render(
      <Provider store={store}>
        <App />
      </Provider>,
      document.getElementById('root')
    )
    

    然后,在另一个你想使用 redux 优点的组件中:

    const Component = ...
    
    const mapStateToProps = (state) => ({
        value: state.someValueFromState
    });
    
    const mapDispatchToProps = { action, otherAction };
    
    export default connect(
      mapStateToProps,
      mapDispatchToProps
      // or you can use action creators directly instead of mapDispatchToProps
      // { action, otherAction }
    )(Component);
    

    然后,您可以在Component 中使用您的动作创建者和状态值作为道具。

    【讨论】:

      【解决方案2】:

      &lt;Provider&gt; 组件特定于官方 React-Redux 绑定器。因此,如果您使用 React-Redux(而不仅仅是 Redux),请使用 &lt;Provider&gt;&lt;Provider&gt; 组件将确保包含在其中的所有内容都可以访问存储。

      【讨论】:

        【解决方案3】:

        在实际应用程序中,您不应该直接订阅商店。 React-Redux 会为你做到这一点。

        请参阅我们在"Why Use React-Redux?" 上的新文档页面以获得更多解释,以及我最近的帖子Idiomatic Redux: The History and Implementation of React-Redux 以了解 React-Redux 所做的一些工作的详细信息,以便您不必这样做。

        【讨论】:

          猜你喜欢
          • 2022-11-02
          • 2022-07-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-20
          • 2016-08-06
          相关资源
          最近更新 更多