Used to avoid repeated rendering (execute render function) and improve efficiency
2 problems with Component
-
When the method setState({}) is run in the component. Even if the parameter of this method is an empty object, the component and its subcomponents will be re-rendered
-
Only the current component re-render() will automatically re-render the sub-component ==> low efficiency
Efficient practice
- Only re-render() when the component's state or props data changes
reason
- shouldComponentUpdate() in Component always returns true
Solution
Method 1:
RewriteshouldComponentUpdate()
the method
to compare the old and new state or props data, and return true if there is a change, and return false if there is no
method 2: Rewrite
using PureComponent , only return true if there is a change in the state or props data Note: only state and props Shallow comparison of data, if only the internal data of the data object has changed, return false and do not modify the state data directly, but generate new data. PureComponent is generally used for optimization in projectsPureComponent
shouldComponentUpdate()
(1) PureComponent comes from the React component library
(2) PureComponent has a problem. If the parameter of setState is the same object as this.state, the component will not be updated. Need to use pure function
state = {
username: "Tom",
};
handExchange = () => {
let obj = this.state;
obj.username = "jack"
this.setState({
obj });
};
shouldComponentUpdate(nextProps, nextState) {
console.log(nextProps);
console.log(nextState);
return true;
}
should be changed to
state = {
username: "Tom",
};
handExchange = () => {
let {
username} = this.state;
username = "jack"
this.setState({
username });
};
shouldComponentUpdate(nextProps, nextState) {
console.log(nextProps);
console.log(nextState);
return true;
}