美文网首页
react16.3的memo特性的使用

react16.3的memo特性的使用

作者: 单只蝴蝶_569d | 来源:发表于2020-02-27 22:00 被阅读0次

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>
    }
}

相关文章

  • react16.3的memo特性的使用

    memo特性是react16.3以后才支持的属性,这个是为了解决react组件树中,state中一直值改变,整个组...

  • React生命周期简介

    首先介绍react16.3之前的生命周期;之后介绍react16.3的生命周期的变化 react16.3之前的生命...

  • React Hook

    0. 边缘知识补充 react16.8出的新特性,在react16.3版本时推出一个新的调和算法 Fiber Re...

  • antd table edit

    antd-editTable 使用antd实现表格增、删、编辑,分别基于react16.2和react16.3实现...

  • 封装了一个react下拉刷新上拉加载组件

    useState,useEffect,React.memo,Ts 使用等

  • react性能优化技巧

    1.使用纯组件2.使用 React.memo 进行组件记忆3.使用 shouldComponentUpdate 生...

  • React中_函数(memo)和class(PureCompon

    memo 只能是函数组件可以使用的,类组件(class)是用不了的 所有的函数组件都是可以包裹一个memo函数的 ...

  • React v16 Fiber

    React在v16推出了很多让我很惊喜的新特性:memo,lazy,Suspense,Hook等当然,其中最让我惊...

  • React 性能优化方向

    1.使用 React.memo 缓存 组件 2.使用 useMemo 缓存值 3.使用 useCallback 缓存函数

  • 使用memo优化遇到的问题

    问题描述:下面是一个全选按钮组件Unlimited,可以传入一个点击事件,一个checked选中状态. 在组件中我...

网友评论

      本文标题:react16.3的memo特性的使用

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