//使用React普通函数时,可以使用两种优化方式,PureComponent和shouldComponentUpdate
//shouldComponentUpdate
//shouldComponentUpdate class Foo extends Component { shouldComponentUpdate(nextProps,nextState){ if(nextProps.count===this.props.count){ //传入的count与组件当前props的count比较,count没改变,return false,不渲染 return false //不渲染 } return true; //渲染 } render() { console.log("组件渲染"); //可以看到,当父组件的name改变时,子组件不会打印,只有count改变,才会打印,优化性能 return null } } class App extends Component { state = { count: 0, name: 0 } render() { return ( <Fragment> <Foo count={this.state.count} ></Foo> <button onClick={() => { this.setState(() => ({ count:this.state.count+1 })) }}>加count</button> <button onClick={() => { this.setState(() => ({ name: this.state.count+1 })) }}>加name</button> </Fragment> ) } }
//PureComponent
//引入PureComponent import React, { Component, Fragment, PureComponent} from 'react'; //PureComponent,自动比较组件数据是否改变,注意只能比较一层,比如一个对象,对象中的属性改变,他不会重新渲染,只有对象改变,才重新渲染。 class Foo extends PureComponent { render() { console.log("组件渲染"); return null } } class App extends Component { state = { count: 0, name: 0 } render() { return ( <Fragment> <Foo count={this.state.count} ></Foo> <button onClick={() => { this.setState(() => ({ count:this.state.count+1 })) }}>加count</button> <button onClick={() => { this.setState(() => ({ name: this.state.count+1 })) }}>加name</button> </Fragment> ) } }
//hooks 独有优化方式memo
//引入memo import React, { Component, Fragment, memo } from 'react'; //用memo把hooks包裹即可 const Foo = memo(function Foo(props) { console.log("组件渲染"); return <div>count:{props.count}</div> }) class App extends Component { state = { count: 0, name: 0 } render() { return ( <Fragment> <Foo count={this.state.count} ></Foo> <button onClick={() => { this.setState(() => ({ count:this.state.count+1 })) }}>加count</button> <button onClick={() => { this.setState(() => ({ name: this.state.count+1 })) }}>加name</button> </Fragment> ) } }