reactjs – 使用Connect或将数据作为道具传递给子项

我是新来的反应和减少.我有一个场景,其中有这样的嵌套组件.

A> B> C> d

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

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

什么是正确的方法

正如丹麦阿布拉莫夫(Dan Abramov)的作者,在这issue中所说的那样

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.

他还在reddit上提出了一个很好的经验法则

我是这样做的:

  • Start by using one container and several presentational components
  • As presentational component tree grows,“middle” components start to pass too many props down
  • 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
  • Repeat

关于这个,他甚至有tweeted

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().这样做会使组件变得聪明,因为它知道它的道具来自何处.一个愚蠢的组件只有道具,它们可以来自任何地方.智能组件与redux耦合;一个愚蠢的组成部分不是.

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...