目录
1_shouldComponentUpdate、纯组件PureComponent的作用
1_shouldComponentUpdate、纯组件PureComponent的作用
父组件每次state值发生变化时,父组件会重新render,子组件也会跟着重新render,但是有时子组件接收的父组件传递的值根本没变,那子组件就做了无用的重复着渲染。
shouldComponentUpdate、纯组件PureComponent都是用来做性能优化的,这两种方法可以避免子组件做无用的重复渲染,下面通过实例来演示这两种性能优化的方法。
2_实例
创建父组件悟空Wukong、子组件悟饭Wufan、子组件悟天Wutian。
子组件悟饭Wufan的接收的Props会改变,子组件悟天Wutian接收的Props不会改变(具体看代码)。
在第一次render后,通过componentDidMount方法,用setInterval方法每1秒更新一次skillOne的值,三秒后用clearInterval方法来停止这个执行操作。
详细代码如下。
父组件悟空Wukong.js:
import React, { Component } from 'react';
import Wutian from './Wutian'
import Wufan from './Wufan'
class Wukong extends Component {
constructor(props) {
super(props);
this.state = {
skillOne:Math.random(),
skillTwo:Math.random()
}
}
componentDidMount(){
// 疑问: