This article mainly introduces the introduction of PureComponent in React, which has certain reference value. Now I share it with everyone. Friends in need can refer to it
React avoids repeated rendering
React builds and maintains an inner implementation within the rendered UI, which includes React elements returned from components. This implementation allows React to avoid unnecessary creation and association of DOM nodes, because doing so may be slower than directly manipulating JavaScript objects. It is called a "virtual DOM".
When a component's props or state change, React determines whether it is necessary to update the actual DOM by comparing the newly returned element with the previously rendered element. When they are not equal, React updates the DOM.
In some cases, your component can improve speed by overriding the shouldComponentUpdate lifecycle function, which is triggered before the re-rendering process begins. This function returns true by default, which allows React to perform updates:
1 2 3 | shouldComponentUpdate(nextProps, nextState) {
return true;
}
|
Copy after login
Example
If you want the component to be only in props.color
or state.count## To re-render when the value of # changes, you can set
shouldComponentUpdate like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class CounterButton extends React.Component {
constructor(props) {
super(props);
this.state = { count : 1};
}
shouldComponentUpdate(nextProps, nextState) {
if (this.props.color !== nextProps.color) {
return true;
}
if (this.state. count !== nextState. count ) {
return true;
}
return false;
}
render() {
return (
<button
color={this.props.color}
onClick={() => this.setState(state => ({ count : state. count + 1}))}>
Count : {this.state. count }
</button>
);
}
}
|
Copy after login
In the above code,
shouldComponentUpdate only checks
props.color Changes in and
state.count. If these values do not change, the component will not be updated. As your components become more complex, you can use a similar pattern to do a "shallow comparison" of properties and values to determine whether the component needs to be updated. This pattern is so common that React provides a helper object to implement this logic - inherited from
React.PureComponent. The following code can more easily achieve the same operation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class CounterButton extends React.PureComponent {
constructor(props) {
super(props);
this.state = { count : 1};
}
render() {
return (
<button
color={this.props.color}
onClick={() => this.setState(state => ({ count : state. count + 1}))}>
Count : {this.state. count }
</button>
);
}
}
|
Copy after login
PureComponent
Principle
When the component is updated, if the props and state of the component have not changed, the render method It will not be triggered, eliminating the generation and comparison process of Virtual DOM to achieve the purpose of improving performance. Specifically, React automatically does a shallow comparison for us:
1 2 3 | if (this._compositeType === CompositeTypes.PureClass) {
shouldUpdate = !shallowEqual(prevProps, nextProps) || !shallowEqual(inst.state, nextState);
}
|
Copy after login
And what does shallowEqual do? It will compare whether the length of Object.keys(state | props) is consistent, whether each key has both, and whether it is a reference, that is, only the value of the first level is compared, which is indeed very shallow, so deep nesting The data cannot be compared.
Question
In most cases, you can use React.PureComponent without having to write your own shouldComponentUpdate, which only does a shallow comparison. But since shallow comparison ignores attributes or state
mutations, you cannot use it at this time.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | class ListOfWords extends React.PureComponent {
render() {
return <p>{this.props.words.join( ',' )}</p>;
}
}
class WordAdder extends React.Component {
constructor(props) {
super(props);
this.state = {
words: [ 'marklar' ]
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
const words = this.state.words;
words.push( 'marklar' );
this.setState({words: words});
}
render() {
return (
<p>
<button onClick={this.handleClick} />
<ListOfWords words={this.state.words} />
</p>
);
}
}
|
Copy after login
In ListOfWords, this.props.words is a reference to its state passed in WordAdder. Although it was changed in the handleClick method of WordAdder, for ListOfWords, its reference remains unchanged, resulting in it not being updated.
Solution
It can be found in the above problem that when a data is immutable data, a reference can be used. But for a mutable data, it cannot be given to PureComponent by reference. To put it simply, when we modify the data used by PureComponent in the outer layer, we should assign it a new object or reference to ensure that it can be re-rendered. For example, handleClick in the above example can be modified through the following to confirm correct rendering:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | handleClick() {
this.setState(prevState => ({
words: prevState.words.concat([ 'marklar' ])
}));
}
或者
handleClick() {
this.setState(prevState => ({
words: [...prevState.words, 'marklar' ],
}));
};
或者针对对象结构:
function updateColorMap(oldObj) {
return Object.assign({}, oldObj, {key: new value});
}
|
Copy after login
immutable.js
Immutable.js is another way to solve this problem. It provides immutable, durable collections through structure sharing:
- Immutable: Once created, a collection cannot be changed at another point in time.
- Persistence: New collections can be created using the original collection and a mutation. The original collection remains available after the new collection is created.
- Structure sharing: The new collection is created using as much of the structure of the original collection as possible to minimize copy operations and improve performance.
1 2 3 4 5 6 7 8 9 10 11 12 | const x = { foo: 'bar' };
const y = x;
y.foo = 'baz' ;
x === y;
const SomeRecord = Immutable.Record({ foo: null });
const x = new SomeRecord({ foo: 'bar' });
const y = x.set( 'foo' , 'baz' );
x === y;
|
Copy after login
Summary
PureComponent What really works is only on some pure display components. If complex components are used
shallowEqual It’s basically impossible to pass that level. In addition, in order to ensure correct rendering during use, remember that
props and
state cannot use the same reference.
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
##ztree obtains json through ajax and checks it checkbook
The above is the detailed content of Introduction to PureComponent in React. For more information, please follow other related articles on the PHP Chinese website!