什么时候应该将组件连接到 redux?

When should connect components to redux in react?

例如,我有这样的组件结构:

<Parent>
      <Child_1>
            <InnerChild_1 />
      </Chidl_1>
      <Child_2>
            <InnerChild_2 />
      </Chidl_2>
</Parent>

组件 <Parent> 连接到 redux。用应用程序状态更新 <InnerChild_1 />,使用 props<Parent> 发送此数据或将 <InnerChild_1 /> 连接到 redux 有什么更好的方法?如果连接,我应该将所有使用状态的组件连接到 redux 吗?

您可以使用扩展运算符 (...props) 或上下文。

通过点差看起来像这样:

<InnerChild_1 
    {...this.props}
/>

恕我直言,最好将 connect 用于 Containers 而不是 Components

Container 持有组件。因此 connect redux 状态到 Container 又将状态发送到 Components 作为 props.

在您的情况下,您可以假设 <Parent />Container,其余子项为组件。

根据我的经验,您应该始终尝试在您的应用程序中尽可能少地使用 redux。根据经验,始终选择将 props 沿组件链向下传递,而不是在子组件中分派操作。对我来说,当你需要跨多个容器组件共享状态时,redux 真的很出色。一个典型的用例是电子商务应用程序中的 authentication/user 数据。在您的情况下,我可以肯定地说 connect 使用您的子组件只会导致不必要的间接访问。

尽管所有其他答案都说明您应该 connect 最高级别,但这确实是一个旧建议,仅对非常简单的应用程序有用。

在需要保持组件与 Redux 存储同步的任何地方使用 connect。在你的例子中,如果 <Parent /> 没有使用任何状态并且它的角色只是组合的,我不会连接那个。我会保留 Parent 一个标准的 React 组件,并单独连接子项。

对于大列表或具有嵌套实体的复杂数据结构,这是可行的方法。

如果您选择另一种方式,并连接到最顶层的组件,那么 任何 状态更改都会导致组件树完全重新渲染,没有自动优化。因为 connected 组件将为你实现 shouldComponentUpdate,你通常会获得更好的性能,将多个项目连接到商店而不是连接 "list" 父级并在每个上重新渲染每个项目改变。

查看 Redux 文档中的 React-Redux 常见问题解答: http://redux.js.org/docs/faq/ReactRedux.html#react-multiple-components

具体来说:

Early Redux documentation advised that you should only have a few connected components near the top of your component tree. However, time and experience has shown that that generally requires a few components to know too much about the data requirements of all their descendants, and forces them to pass down a confusing number of props.