简体   繁体   English

为什么建议React的PureComponent使其所有子级“纯净”

[英]Why React's PureComponent is recommended to have all its children “pure”

Having read the official React documentation , I've came across this regarding PureComponent : 看了官方的阵营文件 ,我已经遇到了这个关于PureComponent:

Furthermore, React.PureComponent's shouldComponentUpdate() skips prop updates for the whole component subtree. 此外,React.PureComponent的shouldComponentUpdate()会跳过整个组件子树的道具更新。 Make sure all the children components are also “pure”. 确保所有子组件也都是“纯”的。

Why exactly does skipping props updates for the whole subtree means avoiding non-pure components? 为什么完全跳过整个子树的props更新意味着避免使用非纯组件? what would be the consequences of a non-pure component inside a PureComponent's component subtree (both in general and in the case when it's not designed/supposed to respond to props change). PureComponent的组件子树中的非纯组件会产生什么后果(一般而言,以及在未设计/不应对道具更改做出响应的情况下)。

A Pure Component for the same set of input props will give absolutely the same result, not just for itself but for the entire DOM tree. 同一组输入道具的Pure Component不仅会给自己,而且会给整个DOM树带来绝对相同的结果。 When you declare a PureComponent , not only do you need to think about props and state , but also context . 声明PureComponent ,不仅需要考虑道具和state ,还需要考虑context PureComponents Block any context changes. PureComponents阻止任何上下文更改。 Consider an example 考虑一个例子

<MyApp>      
 <Router>    // react-router.
  <App>   // A PureComponent
   <Switch>  // react-router Switch
     <Route ....>
   </Switch>
  </App>
 </Router>
</MyApp>

React-router's Router will store current location in router props of context. React-router的Router将当前位置存储在上下文的路由器props中。 And React-router's Switch will read it back and choose a Route.But since App is a very pure component, and will not react to context change in Router, because it not using that values and should ignore them. React-router的Switch会读回它并选择一个Route,但是由于App是一个非常纯的组件,并且不会对Router中的context更改做出反应,因为它not using该值并且应该忽略它们。 And hence when you have a PureComponent in place, you should think about not only the component but also its nested children. 因此,当您拥有一个PureComponent时,您不仅应考虑该组件,还应考虑其嵌套子代。 So essentially you would also keep all your children Pure. 因此,从根本上讲,您还将使所有孩子保持纯洁。

Each prop should be immutable. 每个道具应该是不变的。 It needs to easier debug. 它需要更容易调试。 For example. 例如。 You put array of users via props. 您通过道具放置了一系列用户。 But, one of components do: user.name = value. 但是,组件之一是:user.name = value。 Children components may be much, and you will difficult understand, what is component updates the user? 子组件可能很多,您将很难理解,什么是组件更新用户?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM