为什么 redux 建议只连接顶级组件? [英] Why redux suggests to only connect to top level components?

查看:31
本文介绍了为什么 redux 建议只连接顶级组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 redux 和 react-redux 的新手,同时我正在尝试制作一个 redux 应用程序.

I'm new to redux and react-redux, in the mean time I am trying to make a redux app.

我不明白 redux 文档上的声明:

I don't understand the statement on redux document:

然后,我们使用 react-redux 中的 connect() 函数包装要连接到 Redux 的组件.尝试仅对顶级组件或路由处理程序执行此操作.虽然从技术上讲,您可以将应用中的任何组件 connect() 到 Redux 商店,但请避免这样做太深,因为这会使数据流更难追踪.

Then, we wrap the components we want to connect to Redux with the connect() function from react-redux. Try to only do this for a top-level component, or route handlers. While technically you can connect() any component in your app to Redux store, avoid doing this too deeply, because it will make the data flow harder to trace.

连接所有组件不是更容易,当状态更新时,每个组件都可以获得新的状态树吗?

Isn't it easier to connect to all components and when state is updated, every component can get the new state tree?

为什么是哑组件和高级容器?

Why dumb components and high level containers?

谢谢.

推荐答案

如前所述,Abramov(Redux 的作者)已经回溯了他的建议:connect()ed 组件.他在这篇关于该主题的 Reddit 帖子中阐述了一个很好的经验法则:

As mentioned, Abramov (Redux author) has walked-back his advice re: connect()ed components. He articulates a nice rule of thumb in this Reddit post on the topic:

我是这样做的:

  1. 从使用一个容器和多个展示组件开始

  1. Start by using one container and several presentational components

随着展示组件树的增长,中间"组件开始向下传递过多的 props

As presentational component tree grows, "middle" components start to pass too many props down

此时,我将一些叶子组件包装到容器中,这样中间"组件就不需要接受和传递与它们完全无关的 props

At this point, I wrap some leaf components into containers so that "middle" components don’t need to accept and pass down props that are completely unrelated to them

重复

如果您在 Egghead 上观看我课程中的最后十个视频,这正是我演示的方法:https://egghead.io/series/getting-started-with-redux

If you watch the last ten videos from my course on Egghead, this is exactly the approach I demonstrate: https://egghead.io/series/getting-started-with-redux

根据我的阅读,关于 connect() 的最初建议与性能无关,而与模块化组件有关.易于理解大型应用中的数据流.

From my reading, the initial advice on connect() had nothing to do w/ performance and everything to do with modular components & ease-of-reasoning about data flow in larger apps.

事实上,与 1-container-to-rule-them-all 头重脚轻的模式相比,更多 connect()ed 组件可能是一个性能优势.阿布拉莫夫再次:

In fact, more connect()ed components might be a performance advantage vs. the 1-container-to-rule-them-all top-heavy pattern. Abramov once more:

这两种方法都很好,嵌套的 connect() 组件实际上会给你更多的性能.缺点是它们与应用程序的耦合度稍高,测试难度稍大,但这可能不是什么大问题.

Both approaches are fine, and having nested connect() components is actually going to give you more performance. The downside is they're slightly more coupled to the application and slightly harder to test, but that may not be a big issue.

这篇关于为什么 redux 建议只连接顶级组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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