react-SCU

7/19/2020 react

# react-SCU


shouldComponentUpdate简称SCU

当执行setState()方法时(当一个组件props,state变更),react 会将最新返回的元素与之前的元素做对比,来决定是否有必要更新DOM,当不相同时,会更新DOM,只是更新DOM节点,会有一定的开销,可以通过覆盖生命周期方法 shouldComponentUpdate 来进行优化性能,shouldComponentUpdate()函数返回true时,才会触发render钩子。该方法会在重新渲染前被触发。其默认实现总是返回 true

shouldComponentUpdate(nextProps, nextState) {
  return true;
}

// nextProps: 表示下一个props。
// nextState: 表示下一个state的值。
1
2
3
4
5
6

parent 组件

import React from 'react'

import SCUson1 from './SCUson1'
import SCUson2 from './SCUson2'

class SCU extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            name: 'zhangsan',
            count: 0
        }
    }

    handleClick = () =>{
        this.setState({
            name: 'lisi',
            count: 9
        })
    }

    shouldComponentUpdate(nextProps,nextState){
        if(this.state.name !== nextState.name){
            return true
        }
        return false
    }



    componentDidMount(){
        let i = 0;
        setInterval(() => {
            console.log(i)
            if(i % 5 === 0){
                this.setState({
                    name: 'lisi',
                    count: 99
                })    
            }else{
                this.setState({
                    name: this.state.name,
                    count: this.state.count
                })
            }
            i++
        }, 1000);
    }




    render(){
        console.log('父组件渲染了')
        return <>
            <div>我是父组件</div>
            name: {this.state.name} --- count: {this.state.count}
            <button onClick={this.handleClick}>父组件 SCU 添加</button>
            <hr />
            <SCUson1 count={this.state.count} />
        </>
    }   
}
export default SCU
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

son组件

import React from 'react'


class SCUson1 extends React.Component {



    shouldComponentUpdate(nextProps,nextState){
        if(this.props.count !== nextProps.count){
            return true
        }
        return false
    }

    render(){
        console.log("组件SCUson1 更新了")
        return <>
            <div>我是SCUson1组件</div>
            {this.props.count}
        </>
    }

    
}

export default SCUson1
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
更新: 7/29/2022, 4:33:42 PM