1.使用shouldComponentUpdate生命周期函数

可以在子组件中使用shouldComponentUpdate函数进行判断,如果props和state没有发生改变,则返回false,避免重复渲染。

例如:

class ChildComponent extends React.Component {
  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.someProp === nextProps.someProp && this.state.someState === nextState.someState) {
      return false;
    }
    return true;
  }
  render() {
    return (
      //子组件内容
    );
  }
}

2.使用PureComponent

PureComponent是React中的一个高阶组件,他可以帮助我们判断props和state是否有变化,如果没有变化则不进行重新渲染。

例如:

class ChildComponent extends React.PureComponent {
  render() {
    return (
      //子组件内容
    );
  }
}

3.使用memo

memo是React中的另一个高阶组件,他可以将函数组件转换为具有相同props的纯组件,避免重复渲染。

例如:

const ChildComponent = React.memo(function({ someProp }) {
  return (
    //子组件内容
  );
});
如何避免react子组件重复渲染

原文地址: http://www.cveoy.top/t/topic/BbN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录