控制渲染
Class 组件
-
使用
shouldComponentUpdate
生命周期,return false
import React, { Component } from 'react'; export class ChildLife extends Component { constructor(props) { super(props); this.state = { count: 1 }; } shouldComponentUpdate(nextProps, nextState) { console.log(this.props, nextProps); if (this.props.style.color !== nextProps.style.color) { // 比较新旧props,决定是否重新渲染组件 return true; } if (this.state.count !== nextState.count) { return true; } return false; } render() { console.log('ChildLife render'); return ( <div> <button onClick={() => this.setState((state) => ({ count: state.count + 1 }))}>Count: {this.state.count}</button> <h2 style={this.props.style}>ChildLife</h2> </div> ); } } export default ChildLife;
import React, { Component } from 'react'; import ChildLife from './ChildLife'; export class Demo extends Component { childStyle = { color: 'pink' }; onClick = () => { this.setState({}); }; render() { return ( <> <button onClick={this.onClick}>test</button> <ChildLife style={this.childStyle} /> </> ); } } export default Demo;
-
继承
React.PureComponent
只要prop
没有改变(浅比较),就不会执行render
函数-
PureComponent
: 如果一个组件只和props
和state
有关系,给定相同的props
和state
机会渲染相同的结果,这个组件就叫作纯组件 -
由于只是浅比较,对于数据结构足够复杂(比如对象或数组,修改其中某一个项的值或push一个值并不会触发更新),当然这种情况可以通过对props和state的正确使用来避免,使用concat或赋值一个新对象来触发重新渲染。
this.setState(state => ({ words: state.words.concat(['marklar']) })); this.setState(state => ({ words: [...state.words, 'marklar'], }));
import React from 'react'; export class ChildPure extends React.PureComponent { render() { console.log('child render PureComponent'); return <h2 style={this.props.style}>PureComponent</h2>; } } export default ChildPure;
import React, { Component } from 'react'; import ChildPure from './ChildPure'; export class Demo extends Component { childStyle = { color: 'pink' }; onClick = () => { this.setState({}); }; render() { return ( <> <button onClick={this.onClick}>test</button> <ChildPure style={this.childStyle} /> </> ); } } export default Demo;
-
Function 组件
-
React.memo
包裹组件函数,props
没有改变就不会执行函数import React from 'react'; function ChildMemo({ seconds }) { console.log('I am rendering'); return <div>I am update every {seconds} seconds</div>; } export default React.memo(ChildMemo); // export default ChildMemo;
import React, { Component } from 'react'; import ChildMemo from './ChildMemo'; export class Demo extends Component { childStyle = { color: 'pink' }; onClick = () => { this.setState({}); }; render() { return ( <> <button onClick={this.onClick}>test</button> <ChildMemo seconds={1}/> </> ); } } export default Demo;
- 自定义判断更新条件;
import React from 'react'; function ChildMemo({ seconds }) { console.log('I am rendering'); return <div>I am update every {seconds} seconds</div>; } function areEqual(prevProps, nextProps) { if (prevProps.seconds === nextProps.seconds) { return true; } else { return false; } } export default React.memo(ChildMemo, areEqual);