Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to prevent invalid re-rendering in react

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

Today, the editor will share with you the relevant knowledge points about how to prevent invalid re-rendering in react. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look.

In the process of developing React components, we often encounter this question: under what circumstances will the component be re-rendered?

When the internal data changes, the state changes (by calling this.setState ()), and the props passed by the parent component changes, it causes the component to re-render.

The following questions are also worthy of our consideration:

Does the setState () function cause the component to re-render in any case? What if the state in setState hasn't changed?

If both the state and the props passed from the parent component remain the same, is it certain that there will be no rerendering?

First of all, let's solve these two problems.

Does this.setState (), which does not cause a change in the value of state, cause re-rendering-yes

Import React from 'react'class Test extends React.Component {constructor (props) {super (props) This.state = {Number:1// set the number value in state to 1}} / / setState is called here but does not change the value in setState handleClick = () = > {const preNumber = this.state.Number this.setState ({Number:this.state.Number})} render () {/ / when the render function is called, print the current Number console.log (this.state.Number) return ({this.state.Number})}}

As can be seen from the print results of the console: 1 has been printed 15 times, but the component has not changed!

Such a result is not what we want, so how to prevent the component from being re-rendered? Then we think of one of React's life cycle hooks, shouldComponentUpdate.

There is such a hook in the react life cycle, called the shouldComponentUpdate function, which is called before the render () function is called when re-rendering.

Two parameters, nextProps and nextState, represent the values of the next props and state, respectively.

When the function returns false, block the next call to the render () function, prevent the component from rendering again, and render as usual when the true is returned.

/ / add the shouldComponentUpdate hook / / judge before the render function call: if the Number in the state remains unchanged, block the render from calling shouldComponentUpdate (nextProps,nextState) {if (nextState.Number = = this.state.Number) {return false}} through return false.

After adding the above code, open the console and click the button, which means that the invalid re-rendering has been blocked by us.

The second question is, the state of the component and the props passed from the parent component have not changed. Will the component be re-rendered?-maybe.

It can also be blocked with shouldComponentUpdate hooks.

So, setState that does not change the value of state before and after and numerous re-rendering of the exchanged parent components will lead to component re-rendering, but we can use shouldComponentUpdate to prevent these two situations.

ShouldComponentUpdate is not perfect and can only block flat objects.

NextState.Number = = this.state.Number

If the invocation level is deep

NextState.NumberObject.number = = this.state.NumberObject.number

Number is a numeric variable

NumberObject is an object

The memory storage mechanism of numeric variable (number type) and object (Object) type is different.

At this time, because both point to the same object in the heap, true shouldComponentUpdate fails all the time.

Js variables are divided into basic types of variables and reference type variables.

For variables of these basic types, number,string,boolean,undefined,null, the values are stored in the stack

For reference type variables such as object,Array,function, references are stored in the stack, while different references can point to the same object in heap memory

So, here's the problem.

How can I get a different NumberObject?

There are four ways:

1. The extended syntax of ES6 Object.assign ()

2. Deep copy / shallow copy or using JSON.parse (JSON.stringify (data)) is equivalent to deep copy, but its use is limited.

3. Introduce the third-party library officially recommended by immutable.js react

4. Inherit the PureComponent component of react (instead of Component)

In js, the advantage of reference type data is that frequent operation data is modified on the basis of the original object, and new objects will not be created, so memory can be used effectively and will not be wasted. This feature is called mutable (variable), but its advantage is also its disadvantage. Too flexible and changeable in complex data scenarios also causes its uncontrollability. Suppose an object is used in many places. If you accidentally modify the data in one place, it is difficult to foresee how the data will change in other places. the solution to this problem, like the example just now, will want to copy a new object and make changes on the new object. this will undoubtedly lead to more performance problems and memory waste.

To solve this problem, the immutable object appears, and each time you modify the immutable object, a new immutable object is created, while the old object does not change.

Immutable.js has three main features:

Persistent data structure (persistent data structure)

Structural sharing (structure sharing)

Support lazy operation (lazy operation)

An Immutable Data is data that, once created, cannot be changed. Any modifications, additions and deletions to the Immutable object return a new Immutable object. The principle of Immutable implementation is Persistent Data Structure (persistent data structure), that is, when creating new data with old data, make sure that the old data is available and unchanged at the same time. At the same time, in order to avoid the performance loss caused by deepCopy copying all the nodes once, Immutable uses Structural Sharing (structure sharing), that is, if one node in the object tree changes, only that node and the parent node affected by it are modified, and other nodes are shared.

The three most important data structures: Map List Set

Map: a collection of key-value pairs, and there is also a special Map object corresponding to Object,ES6

List: an ordered and repeatable list corresponding to Array

Set: unordered and non-repeatable list

/ / Map () Native object to Map object (only convert the first layer, note the difference from fromJS) immutable.Map ({name:'danny', age:18}) / / List () Native array to List object (only convert the first layer, pay attention to the difference from fromJS) immutable.List ([1rem 2m 3J 4J 5]) / / fromJS () Native js to immutable object (depth conversion Will convert all internally nested objects and arrays to immutable) immutable.fromJS ([1pje 2je 3je 4je 5]) / / convert native array-- > Listimmutable.fromJS ({name:'danny', age:18}) / / native object-- > Map//toJS () immutable object to native js (depth conversion, will convert all internally nested Map and List into native js) immutableData.toJS () / / check List or map size immutableData.size or immutableData.count () / / is () to determine whether two immutable objects are equal immutable.is (imA, imB); / / merge () objects merge var imA = immutable.fromJS ({aVl1) bGV 2}); var imA = immutable.fromJS ({CPLV 3}); var imC = imA.merge (imB); console.log (imC.toJS ()) / / {aaVlv ()) / {aaVl1Parv 2)

For two identical data, it is not possible to compare them with each other through equals.

If one is cloned by another, then they are all equal.

Push add unshift add concat combination in the header returns new data, not the length of the data

/ / add, delete, modify and search (all operations will return the new value and will not change the original value) var immutableData = immutable.fromJS ({aVl1, bvar data1 2, c: {DREV 3}}); var data1 = immutableData.get ('a') / / data1 = 1 var data2 = immutableData.getIn (['centering,' d']) / / data2 = 3 getIn for deep structure access var data3 = immutableData.set ('a', 2) A = 2var data4 = immutableData.setIn in / / data3 (['cations,' d'], 4) D = 4var data5 = immutableData.update in data4 (a = 5var data6 = immutableData.updateIn (['return,' d'], function (x) {return xanth4}) in / data5) / / d = 7var data7 = immutableData.delete ('a') / / data7 in var data8 = immutableData.deleteIn (['clocked,' d']) / / there is no replication code in d / data8

Advantages:

Reduce the complexity of mutable

Save memory

Historical traceability (time travel): time travel means that the value of every moment is retained. You can simply take the data out if you want to go back to. Think about it if there is an undo operation on the page now, and the data before undo is retained. You just need to take it out. This feature is particularly useful in redux or flux.

Embrace functional programming: immutable is originally the concept of functional programming. The characteristic of pure functional programming is that as long as the input is consistent, the output must be consistent. Compared with object-oriented, it is more convenient to develop components and debug.

Disadvantages:

Need to relearn api

Resource bundle size increased (about 5000 lines of source code)

It is easy to be confused with native objects: because api is different from native objects, it is easy to make mistakes when mixed.

These are all the contents of the article "how to prevent invalid re-rendering in react". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report