我应该使用 Redux store.subscribe() 还是用 react-redux <Provider> 包装我的应用程序?

Should I use Redux store.subscribe() or wrap my app with react-redux <Provider>?

我见过两种方法: 在 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 包装在一个 <Provider> 组件中。

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

Can/Should 如果我用 <Provider> ?

包装我的应用程序,我会使用 Store.subscribe

<Provider> 组件特定于官方 React-Redux 绑定器。因此,如果您使用的是 React-Redux(而不仅仅是 Redux),请使用 <Provider><Provider> 组件将确保包装在其中的所有内容都可以访问商店。

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

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.

中使用您的动作创建者和状态值作为道具

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

请查看我们在 "Why Use React-Redux?" for some further explanation, as well as my recent post Idiomatic Redux: The History and Implementation of React-Redux 上的新文档页面,了解 React-Redux 所做的一些工作的详细信息,这样您就不必这样做了。