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 (
             <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,组件必须写成函数式组件)。

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

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

  • 使用PureComponent重写Comment组件
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>
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容