在 Redux 中,每个容器都有一个连接? [英] In Redux, there is one connect for each container?

查看:45
本文介绍了在 Redux 中,每个容器都有一个连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我之前的项目中,我通常只有一个connect(mapStateToProps, mapDispatchToProps)(App).但是当我今天查看官方example,我发现每个容器几乎都有一个connect().

In my previous projects, I usually have only one connect(mapStateToProps, mapDispatchToProps)(App). But when I check the official example today, I find there is almost one connect() for each container.

拥有多个connect()有什么好处?

推荐答案

想象一个 Redux 版本的 Stack Overflow 问答页面.您将有很多组件:问题及其投票、答案及其投票、用于其他答案的 Markdown 编辑器、顶部的个人资料链接以及右侧的相关和网络问题.相应的 Redux 存储可以包含活动问题、活动答案、相关问题、用户配置文件和 Markdown 编辑器的子对象.

Imagine a Redux version of Stack Overflow's Q&A page. You'd have quite a few components: the question and its votes, answers and their votes, the Markdown editor for additional answers, the profile link at the top, and related and network questions on the right. The corresponding Redux store could have sub-objects for the active question, active answers, related questions, user profile, and Markdown editor.

正如您所提到的,您可以使用单个顶级 connect,但是 connect 单独使用每个组件可提供 性能封装:

You could use a single top-level connect, as you mentioned, but connecting each component individually offers performance and encapsulation:

  • 单个顶级 connect 意味着只要任何 Redux 存储值发生变化,顶级 App 就会重新渲染,然后它必须将这些 props 传递给它的每个子组件(必须重新渲染或检查 shouldComponentUpdate).如果您分别连接每个组件,那么,例如,当您在 Markdown 编辑器中输入内容并更新编辑器的商店切片时,只有 Markdown 编辑器会重新渲染.
  • 单个顶级connect意味着顶级App需要知道它下面的所有内容,以便它可以传递所有需要的道具和事件本身.单独的connect提供封装:profile bar可以connect到它需要的props和action creators,更高层的组件不需要知道或关心详情.
  • A single top-level connect means that the top-level App gets re-rendered whenever any Redux store value changes, then it has to pass down those props to each of its child components (which either have to re-render or check shouldComponentUpdate). If you connect each component separately, then, e.g., when you type something in the Markdown editor and update the editor's slice of the store, only the Markdown editor re-renders.
  • A single top-level connect means that the top-level App needs to know everything under it, so that it can pass down all of the needed props and events itself. Individual connects offer encapsulation: the profile bar can connect to the props and action creators that it needs, and higher-level components don't have to know or care about the details.

这篇关于在 Redux 中,每个容器都有一个连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆