简体   繁体   English

反应阻止来自父容器的子更新

[英]react prevent child update from parent container

I'm using a react color picker that changes the state on change (so many times per second).我正在使用一个反应颜色选择器,它在变化时改变状态(每秒很多次)。 since the state changes my component, and all of its children are being rerendered.因为状态改变了我的组件,并且它的所有子组件都被重新渲染。 I don't have any control over the children as they're imported from other libraries (reactstrap and react-fontawesome) so I need a way to prevent these from updating from the parent containers.我无法控制子项,因为它们是从其他库(reactstrap 和 react-fontawesome)导入的,因此我需要一种方法来防止它们从父容器中更新。

I could create a wrapper component with a custom shouldComponentUpdate() but that solution seems kind of hacky so I'm curious if there's an intended solution for this.我可以创建一个带有自定义shouldComponentUpdate()的包装器组件,但该解决方案似乎有点shouldComponentUpdate() ,所以我很好奇是否有针对此的预期解决方案。

relevant parts of my code:我的代码的相关部分:

//all components come from libraries so I have no control over them
    <SketchPicker
       color={this.state.color}
       onChange={this.handleChangeColor}
    />

  handleChangeColor = color => {
    this.setState({ color: color.rgb });
  };

//rest of the code is made of multiple
 <NavItem>
  <NavLink ... >
    <FontAwesomeIcon ... />
  </NavLink>
</NavItem>

some of my navItems rely on the real time color information but most of them dont我的一些导航项目依赖于实时颜色信息,但大多数不依赖

If the props you're passing down are not changing you can indeed use shouldComponentUpdate or even better React.PureComponent .如果你传递的 props 没有改变,你确实可以使用shouldComponentUpdate甚至更好的React.PureComponent PureComponent children won't re-render if the props passed from top level are the same as the previous props.如果从顶层传递的 props 与之前的 props 相同,PureComponent 子组件将不会重新渲染。 The comparison is shallow so it wouldn't work for deeply nested props.比较是肤浅的,因此它不适用于深度嵌套的道具。

Read more here . 在这里阅读更多。

I you use redux you can use reselect .我你使用 redux 你可以使用reselect A selector (props essentially) is not recomputed unless one of its arguments changes.除非参数之一发生变化,否则不会重新计算选择器(本质上是道具)。

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

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