A> B> C> d
A组件中使用了一个属性,它将用于D组件.所以,我有两种方法:
>从组件A中的redux store获取状态,然后将其作为props传递给它的所有子组件,即使它只在D组件中使用.
>我应该连接到组件D中的redux store并从那里获取该属性.
什么是正确的方法?
Both approaches of passing props down to children or connecting them
to the store are appropriate,however having nestedconnect()
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耦合;一个愚蠢的组成部分不是.