React updates a component whenever any state
or props
variable changes.
So, to prevent a re-render conditionally, you can use this lifecycle function (returning false
means avoiding a re-render):
class component
shouldComponentUpdate(prevState, prevProps) {
if (this.state.someVariable !== prevState.someVariable ||
this.props.someVariable !== prevProps.someVariable) {
return false;
}
return true;
}
functional component
React.memo(MyComponent, (props, nextProps)=> {
if(this.state.someVariable !== prevState.someVariable) {
// if don't re-render/update
return true
}
//...
})
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…