- PureComponent适用于展示型组件
- PureComponent在渲染前会进行浅比较,即比较props和state,来实现shouldComponentUpdate的效果。
- shouldComponentUpdate 用在component中,如果出现不想在某些情况下渲染,用它来实现比较。用在PureCommonent中是无效的,因为PureCommonent自己本来会进行浅比较操作。
- 如果组件继承自PureComponent,首次会执行constructor和render,二次执行操作,看数据操作类型:
1):数组或对象,引用不同,才会render,
eg: this.setState({ array }); × this.setState({ array: […array, 2] }); √ - PureCommonent 的影响:
1):父组件继承自PureCommonent,子组件继承自commonent,二次执行,不渲染,因为父组件的属性引用无变化,子组件接受的属性也无变化。
2):父组件继承自PureCommonent, 子组件继承自PureCommonent,二次操作不render,父组件在比较时已经阻止了此操作。
3):父组件继承自commonent,子组件继承自PureCommonent,如果引用发生变化,则父子组件render;如果引用不变化,则子组件不render。
4):父组件继承自commonent,子组件继承自commonent,则父子组件均render。
PureCommonent 的影响://父组件import React, { PureComponent, Component } from 'react';import Example from "../components/Example";class IndexPage extends PureComponent{ constructor() { super(); this.state = { person: { name: 'sxt' } }; console.log('constructor'); } changeState = () => { let { person } = this.state; person.name = 'sxt2'; this.setState({ person }) }; render() { console.log('IndexPage render'); const { person } = this.state; return ( <div> <button onClick={this.changeState}>点击</button> <Example person={person} /> </div> ); }}//子组件import React, { Component } from 'react';class Example extends Component { render() { console.log('example render'); const { person } = this.props; return( <div> {person.name} </div> ); }}