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

前端之家收集整理的这篇文章主要介绍了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相关文章