使用 Connect 或将数据作为道具传递给孩子 [英] Use Connect or pass data as props to children

查看:34
本文介绍了使用 Connect 或将数据作为道具传递给孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 React 和 Redux 的新手.我有一个场景,其中有这样的嵌套组件.

I am new to react and redux. I have a scenario where there are nested components like this.

A>B>C>D

A 组件中使用了一个属性,它将在 D 组件中使用.所以,我有两种方法:

There is a property used in A component and it will be used in D component. So, I have two approaches:

  1. 从组件 A 的 redux 存储中获取状态,然后将其作为道具传递给它的所有子组件,即使它只会在 D 组件中使用.
  2. 我应该连接到组件 D 中的 redux 存储并从那里获取该属性.

正确的方法是什么?

推荐答案

正如 Redux 的作者 Dan Abramov 在这篇文章中所说的那样问题

As Dan Abramov, author of redux says in this issue

将道具传递给孩子或将他们连接起来的两种方法到商店是合适的,但是嵌套 connect()组件实际上会给你更多的性能.这缺点是它们与应用程序的耦合度略高,并且测试稍微困难一些,但这可能不是大问题.

Both approaches of passing props down to children or connecting them to the store are appropriate, however 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.

他还阐明了一个很好的经验法则可以遵循 红迪网

He has also articulated a nice rule of thumb to follow on reddit

我是这样做的:

  • 从使用一个容器和多个展示组件开始
  • 随着展示组件树的增长,中间"组件开始向下传递过多的 props
  • 此时,我将一些叶子组件包装到容器中,以便中间"组件不需要接受和传递与他们完全无关
  • 重复

他甚至推特:

He has even tweeted regarding this:

尽量将您的演示组件分开.创建容器在方便的时候通过连接组件来连接它们.每当你觉得你在父组件中复制代码来为相同类型的子组件提供数据时,是时候提取一个容器了.

Try to keep your presentation components separate. Create container components by connecting them when it’s convenient.Whenever you feel like you’re duplicating code in parent components to provide data for same kinds of children, time to extract a container.

简单来说:

您可以在任何级别使用 connect().这样做会使组件变得智能,因为它知道它的 props 来自哪里.一个哑组件只有道具,它们可以来自任何地方.一个智能组件耦合到 redux;一个哑组件不是.

You can use connect() at any level. Doing so makes the component smart, since it knows where its props come from. A dumb component just has props, and they could come from anywhere. A smart component is coupled to redux; a dumb component is not.

更新:react-redux v7 及以上

同样的概念也适用于 useSelectors.如果多个子组件使用相同的数据,您可以在容器组件中接收数据并将数据传递给您的展示组件

The same concept applies to useSelectors too. You can receive data in a container component and pass on to your presentational components, if multiple of its children make use of the same data

如果子组件使用的数据不同,您可以选择在子组件中单独使用useSelector.这将确保只有那些实际需要重新渲染的组件

If however the data used by the children is different, you can choose to use useSelector individually within the child component. This will make sure that only those components re-render which actually need to

这篇关于使用 Connect 或将数据作为道具传递给孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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