react16.3的memo特性的使用

2020-02-27  本文已影响0人  单只蝴蝶_569d

memo特性是react16.3以后才支持的属性,这个是为了解决react组件树中,state中一直值改变,整个组件树都重新刷新的情况。
例:

class CommentList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            commentList: [{
                body: '大三岁', author: '张三'
            }, {
                body: '新冠病毒', author: '李四'
            }]
        }
    }

    componentWillMount() {
        setTimeout(()=>{
            this.setState((prevState,props)=>{
              return {
                  commentList:[{
                      body: '大三岁', author: '张三'
                  }, {
                      body: '新冠1病毒', author: '李四'
                  }]
              }
            })
        },1000)
    }

    render() {
        return (
             <div>
                {
                    this.state.commentList.map((item, index) => {
                      return  <PureComment {...item} key={index} />
                    })
                }
                }
            </div>
            )

    }
}
function  Comment(props) {
    console.log('渲染了')
    return <div>
         <p>{props.body}</p>
         <p>{props.author}</p>
        </div>
}

看控制台打印出来的渲染日志,你会发现每次改变一个值,2个组件都会刷新。这样,值不改的情况下,也会渲染,会影响到性能。如果组件想要做到,传入的props改变时,组件才会更新,那么我们就可以用react中memo特性(同react16之前的PureComponent,不过用PureComponent,组件必须写成函数式组件)。

const Comment=React.memo((props)=>{
    console.log('渲染了')
    return <div>
          <p>{props.body}</p>
          <p>{props.author}</p>
        </div>
})

会发现只要值改变,组件才会重新渲染。

class PureComment extends  React.PureComponent{

    constructor(){
        super()
    }
    render() {
        console.log('渲染了')
        const props=this.props
        return <div>
            <p>{props.body}</p>
            <p>{props.author}</p>
        </div>
    }
}
上一篇 下一篇

猜你喜欢

热点阅读