美文网首页
react的性能优化

react的性能优化

作者: 水晶草720 | 来源:发表于2022-04-07 17:20 被阅读0次

    1.shouldComponentUpdate

    控件组件自身或者子组件是否需要更新,尤其是在子组件非常多的情况下,需要进行优化。

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

    2.PureComponent

    pureComponent 会帮你 比较新props跟旧的props,新的state 和老的 state(值相等,或者对象含有相同的属性 且属性值相等),决定shouldcomponentUpdate 返回true 或者 false,从而决定要不要呼叫 render function
    //注意 如果你的state 或 props [永远都会变],那PureComponent 并不会比较快,因为shallowEqual 也需要花时间

    
    import React, { PureComponent } from 'react'
    export default class app extends PureComponent {
        state = {
            mytext:"11111"
        }
        render() {
          console.log('render')
        return (
            <div>
                <button onClick={() => this.setState({mytext:"2222"})}>click</button>
                {this.state.mytext}
          </div>
        )
        }
        getSnapshotBeforeUpdate() {
            console.log("getSnapshotBeforeUpdate")
            return 111;
        }
    
        componentDidUpdate(prevProps, prevState,value) {
            console.log("componentDidUpdate",value)
        }
       
    }
    

    相关文章

      网友评论

          本文标题:react的性能优化

          本文链接:https://www.haomeiwen.com/subject/hirssrtx.html