我是靠谱客的博主 温柔长颈鹿,这篇文章主要介绍react性能优化是哪个周期函数,现在分享给大家,希望可以做个参考。

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

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

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

shouldComponentUpdate() 方法格式如下:

复制代码
1
shouldComponentUpdate(nextProps, nextState)
登录后复制

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

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

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!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 时执行的操作(点击按钮可以修改):

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!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性能优化是哪个周期函数的详细内容,更多请关注靠谱客其它相关文章!

最后

以上就是温柔长颈鹿最近收集整理的关于react性能优化是哪个周期函数的全部内容,更多相关react性能优化是哪个周期函数内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(98)

评论列表共有 0 条评论

立即
投稿
返回
顶部