Use shouldComponentUpdate for performance optimization

As we all know, changes in props and state values ​​in react will cause components to re-render. The use of shouldComponentUpdate is to reduce unnecessary rendering of render. This article focuses on answering the following questions:

1: How to use shouldComponentUpdate memory optimization;

shouldComponentUpdate(nexrProps) {
    if (this.props.num === nexrProps.num) {
        return false
    }
    return true;
}

I believe everyone knows this way, shouldComponentUpdate provides two parameters nextProps and nextState, which means the next props and one state value. When the function returns false, the render () method is not executed, and the component will not render, returning true At this time, the component is re-rendered as usual. This method is to compare the value of the current props with the value of the next props. When the data are equal, return false, otherwise return true. However, this method has no effect when facing complex objects. For example, if props grows like this, there is no way to deal with it, because in js, object, array, function are reference types, even if the data in them is changed, they point to It is still the same memory address, so the above judgment will not work.

 obj: {
    age: 12,
    name: 'xioabbao',
    student: {
        count: 1
    }
}

2: There are three solutions:

(1) Before using setState to change data, first use es6 assgin to copy, but assgin only deep copies the first layer of data, so it is not the most perfect solution.

const o2 = Object.assign({},this.state.obj)
    o2.student.count = '00000';
    this.setState({
        obj: o2,
    })

(2) Use JSON.parse (JSON.stringfy ()) for deep copy, but it will be wrong when the data is undefined and function.

const o2 = JSON.parse(JSON.stringify(this.state.obj))
    o2.student.count = '00000';
    this.setState({
        obj: o2,
    })

(3) Use immutable.js to build the project. Immutable pays attention to the immutability of data. Before each operation on the data, it will automatically make a deep copy of the data. The data in the project adopts the immutable method, which can easily solve the problem, but there is another set of APIs to learn.

This article is a personal opinion, I hope you can give me a lot of advice.

Guess you like

Origin www.cnblogs.com/jlfw/p/12740319.html