React之shouldComponentUpdate的用法

简介: React之shouldComponentUpdate的用法

为什么要使用shouldComponentUpdate?

只要是组件继承自React.Component就会存在当父组件重新render的时候,子组件也会重新执行render,即使这个子组件没有任何变化。子组件只要调用setState就会重新执行render,及时setState的参数是一个空对象。

shouldComponentUpdate的用法

在子组件中:

shouldComponentUpdate(nextProps,nextState) {
    if (nextProps.m1 === this.props.m1 && nextState.m2 === this.state.m2) {
        return false;
    } else {
        return true;
    }
}
复制代码

根据下面的React生命周期流程图可知,当shouldComponentUpdate返回为true的时候,当前组件进行render,如果返回的是false则不进行render.

image.png

codeSandBox在线演示

相关文章
|
6月前
react-withRouter 用法
react-withRouter 用法
87 0
|
13天前
|
前端开发 UED
React 防抖与节流用法
React 防抖与节流用法
41 0
|
13天前
|
前端开发 JavaScript
react中refs的作用是什么?有几种用法?
react中refs的作用是什么?有几种用法?
|
13天前
|
存储 前端开发 JavaScript
[React] useRef用法和特性
[React] useRef用法和特性
|
8月前
|
前端开发 JavaScript
React Hooks 用法详解3
React Hooks 用法详解
|
8月前
|
前端开发 JavaScript API
React Hooks 用法详解2
React Hooks 用法详解
|
8月前
|
缓存 前端开发 JavaScript
React Hooks 用法详解1
React Hooks 用法详解
|
9月前
|
前端开发
react中使用shouldComponentUpdate生命周期函数调用setState引起的无限循环的错误
react中使用shouldComponentUpdate生命周期函数调用setState引起的无限循环的错误
86 0
|
9月前
|
存储 缓存 前端开发
React.memo() 和 useMemo() 的用法是什么,有哪些区别?
React.memo() 和 useMemo() 的用法是什么,有哪些区别?
101 0
|
9月前
|
前端开发
前端项目实战壹佰零肆react-admin+material ui-踩坑-List的用法之queryOptions
前端项目实战壹佰零肆react-admin+material ui-踩坑-List的用法之queryOptions
54 0

热门文章

最新文章