用React.memo API解决函数组件多余渲染的问题

引入

学习Hook之后,我了解到useEffect()一般是在组件渲染之后执行的(当然也可以传入
依赖列表来跳过Effect),所以能够起到class组件生命周期方法:
componentDidMount()
componentDidUpdate()
componentWillUnmount()
的作用;

但我没有找到shouldComponentUpdate()的替代方案。
经过官网API文档,了解到React.memo API能够起到类似的效果。

React.memo

React.memo 是高阶组件,所以它是一个函数,它的第一个参数是一个函数组件,
传入的组件被memo包装后它会在每次渲染前检查(浅层)上props的变更,效果类似
PureComponent;
如果想要控制比较的过程,可以给memo传入第二个参数,即
areEqual(prevProps, nextProps)函数。与shouldComponentUpdate()不同的是,
areEqual函数返回true表示跳过渲染。


const Component = (props) => {
    return (
        <div>{props.h1}</div>
    )
} 

function areEqual(prevProps, nextProps) {
    if(preProps.h1 === nextProps.h1) {
        return true;
    } else {
        return false;
    }
}

React.memo(Component, areEqual);

其他体会

在学会用Redux来存储和管理数据之后,我发觉似乎在有些情况下shouldComponentUpdate()的应用场景不大,因为只有当mapStateToProps映射到组件上的props发生变化,才会引起组件重新渲染。

如果组件包含有从父组件传递的props,则使用这种方式优化性能还是很有意义的。

你可能感兴趣的:(React)