react性能优化是哪个周期函数

WBOY
WBOY 原创
2022-05-05 11:00:22 1675浏览

react性能优化是shouldComponentUpdate周期函数;该函数可判断是否需要调用render方法重新描绘dom,能够优化dom diff算法,语法为“shouldComponentUpdate(Props,state)”。

本教程操作环境:Windows10系统、react16.4.0版、Dell G3电脑。

react性能优化是哪个周期函数

shouldComponentUpdate 这个方法用来判断是否需要调用render方法重新描绘dom。因为dom的描绘非常消耗性能,如果我们能在shouldComponentUpdate方法中能够写出更优化的dom diff算法,可以极大的提高性能

shouldComponentUpdate() 方法格式如下:

shouldComponentUpdate(nextProps, nextState)

shouldComponentUpdate() 方法会返回一个布尔值,指定 React 是否应该继续渲染,默认值是 true, 即 state 每次发生变化组件都会重新渲染。

shouldComponentUpdate() 的返回值用于判断 React 组件的输出是否受当前 state 或 props 更改的影响,当 props 或 state 发生变化时,shouldComponentUpdate() 会在渲染执行之前被调用。

以下实例演示了 shouldComponentUpdate() 方法返回 false 时执行的操作(点击按钮无法修改):

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>React 实例</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritesite: "runoob"};
  }
  shouldComponentUpdate() {
    return false;
  }
  changeSite = () => {
    this.setState({favoritesite: "google"});
  }
  render() {
    return (
      <div>
      <h1>我喜欢的网站是 {this.state.favoritesite}</h1>
      <button type="button" onClick={this.changeSite}>修改</button>
      </div>
    );
  }
}
ReactDOM.render(<Header />, document.getElementById('root'));
</script>
</body>
</html>

输出结果:

55555.png

以下实例演示了 shouldComponentUpdate() 方法返回 true 时执行的操作(点击按钮可以修改):

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>React 实例</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritesite: "runoob"};
  }
  shouldComponentUpdate() {
    return true;
  }
  changeSite = () => {
    this.setState({favoritesite: "google"});
  }
  render() {
    return (
      <div>
      <h1>我喜欢的网站是 {this.state.favoritesite}</h1>
      <button type="button" onClick={this.changeSite}>修改</button>
      </div>
    );
  }
}
ReactDOM.render(<Header />, document.getElementById('root'));
</script>
</body>
</html>

输出结果:

66666.png

点击按钮后:

77777.png

推荐学习:《react视频教程

以上就是react性能优化是哪个周期函数的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。