只要执行setState(),即使不改变状态数据, 组件也会重新render() ==> 效率低
只当前组件重新render(), 就会自动重新render子组件,纵使子组件没有用到父组件的任何数据 ==> 效率低
示例代码:
import React, {Component} from 'react';
export default class Parent extends Component {
state = {carName: "奔驰"}
changeCar = () => {
this.setState({carName: "迈巴赫"})
}
render() {
console.log("parent----render");
return (
<div style={{backgroundColor: "red", padding: "0 20px"}}>
<h1>我是father组件</h1>
<p>我的车是:{this.state.carName}</p>
<button onClick={this.changeCar}>点我换车</button>
<Child carName={this.state.carName}/>
</div>
)
}
}
class Child extends Component {
render() {
console.log("render----child");
return (
<div style={{backgroundColor: "gray"}}>
<h3>我是child组件</h3>
<p>我接收到的车是:{this.props.carName}</p>
</div>
)
}
}
只有当组件的state或props数据发生改变时才重新render();
Component中的shouldComponentUpdate()总是返回true;
shouldComponentUpdate()用于控制组件是否更新的阀门;
链接: react的生命周期
重写shouldComponentUpdate()方法;
比较新旧state或props数据, 如果有变化才返回true, 如果没有返回false;
/*可以接收三个参数:
* 1、nextProps
* 2、nextState
* 3、nextContext
* */
shouldComponentUpdate(nextProps, nextState, nextContext) {
console.log(this.props, this.state);//目前的props,和state
console.log(nextProps, nextState);//接下来要变化的目标props,state
if (this.state.carName === nextState.carName) return false
else return true
}
shouldComponentUpdate(nextProps, nextState, nextContext) {
console.log(this.props, this.state);//目前的props,和state
console.log(nextProps, nextState);//接下来要变化的目标props,state
return !this.props.carName === nextProps.carName
}
使用PureComponent,PureComponent重写了shouldComponentUpdate(), 只有state或props数据有变化才返回true
export default class Parent extends PureComponent{
}
class Child extends PureComponent {
}
注意:
只是进行state和props数据的浅比较,
如果只是数据对象内部数据变了, 返回false
,不要直接修改state数据, 而是要产生新数据。项目中一般使用PureComponent来优化。
直接修改数据,没有产生新数据,组件不会重新渲染,state不会更新
const obj = this.state;
obj.carName = "迈巴赫";
console.log(obj === this.state);//true
this.setState(obj)