react16.3的memo特性的使用

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 (
             
{ this.state.commentList.map((item, index) => { return }) } }
) } } function Comment(props) { console.log('渲染了') return

{props.body}

{props.author}

}

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

  • 那么现在使用memo特性将Comment组件重写:
const Comment=React.memo((props)=>{
    console.log('渲染了')
    return 

{props.body}

{props.author}

})

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

  • 使用PureComponent重写Comment组件
class PureComment extends  React.PureComponent{

    constructor(){
        super()
    }
    render() {
        console.log('渲染了')
        const props=this.props
        return 

{props.body}

{props.author}

} }

你可能感兴趣的:(react16.3的memo特性的使用)