Introduction to PureComponent in React

不言
Release: 2018-07-09 16:26:55
Original
1522 people have browsed it

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:

shouldComponentUpdate(nextProps, nextState) { return true; }
Copy after login

Example

If you want the component to be only inprops.colororstate.count## To re-render when the value of # changes, you can setshouldComponentUpdatelike this:

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 (  ); } }
Copy after login
In the above code,

shouldComponentUpdateonly checksprops.color Changes inandstate.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 fromReact.PureComponent. The following code can more easily achieve the same operation:

class CounterButton extends React.PureComponent { constructor(props) { super(props); this.state = {count: 1}; } render() { return (  ); } }
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:

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.

class ListOfWords extends React.PureComponent { render() { return 

{this.props.words.join(',')}

; } } class WordAdder extends React.Component { constructor(props) { super(props); this.state = { words: ['marklar'] }; this.handleClick = this.handleClick.bind(this); } handleClick() { // This section is bad style and causes a bug const words = this.state.words; words.push('marklar'); this.setState({words: words}); } render() { return (

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:

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.

// 常见的js处理 const x = { foo: 'bar' }; const y = x; y.foo = 'baz'; x === y; // true // 使用 immutable.js const SomeRecord = Immutable.Record({ foo: null }); const x = new SomeRecord({ foo: 'bar' }); const y = x.set('foo', 'baz'); x === y; // false
Copy after login
Summary

PureComponentWhat really works is only on some pure display components. If complex components are usedshallowEqualIt’s basically impossible to pass that level. In addition, in order to ensure correct rendering during use, remember thatpropsandstatecannot 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:

The difference between AngularJs and Angular’s commonly used instruction writing methods

##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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!