3

我已经看到了这两种方法:在这个例子中,取自 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() 函数允许添加在调度操作时调用的侦听器。

另一个示例中,这是来自 Redux 文档的示例:

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

不使用 store.subscribe ,而是将整个 App 包装在一个<Provider>组件中。

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

如果我用 包装了我的应用程序,我可以/应该使用 Store.subscribe<Provider>吗?

4

3 回答 3

7

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

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.

于 2018-12-02T14:16:10.667 回答
1

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

于 2018-12-02T13:56:01.730 回答
1

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

请参阅我们关于“为什么使用 React-Redux?”的新文档页面。进一步的解释,以及我最近的帖子Idiomatic Redux: The History and Implementation of React-Redux了解 React-Redux 所做的一些工作的详细信息,以便您不必这样做。

于 2018-12-03T17:15:52.063 回答