美文网首页
React生命周期及减少render次数

React生命周期及减少render次数

作者: 踩坑怪At芬达 | 来源:发表于2020-04-26 18:07 被阅读0次

React生命周期

环境:react16

常用生命周期的钩子分类后,分布3个阶段内

  • 初始化阶段 - 组件创建阶段才会执行

    • componentWillMount
    • componentDidMount
  • 运行期间 - 组件运行阶段根据情况执行

    • componentWillReceiveProps(nextProps):即将用nextProps替换当前组件的props
    • shouldComponentUpdate:this.props或state发生改变时,询问是否需要进行渲染
    • componentWillUpdate(newProps,newState,newContext): this.state 或 this.props 即将发生改变,并准备渲染前,此时this.props和this.state还是老的值
    • componentDidUpdate(oldProps,oldState,Snapshot): 运行期间组件调用render渲染完毕后,此时this.props和this.state已经是最新值,而oldProps和oldState为变更前的值
  • 组件销毁

    • componentWillUnmount
image

父子组件数据变化何时Render?

image
  • 总结几点
    • shouldComponentUpdate 则根据它的返回值判断是否render

      继承自 React.PureComponent的类组件默认就是有shouldComponentUpdate的,只是做了浅对比,我们不需要再显式的写一个shouldComponentUpdate

    • shouldComponentUpdate 则render
    • 父组件不render,子组件也收不到 componentWillReceiveProps
    • 子组件自己render,不影响父组件

如何用简单的方法尽可能减少render提高效率?

1、 使用React.PureComponent代替React.Component

注意在变更属性时要时浅层的值或地址发生改变

2、 自定义shouldComponentUpdate,根据当前组件的属性情况,自行编写哪些属性发生变化时进行render

容易遗忘当前组件不实用的属性,而子组件使用的属性,导致父组件不render,子组件也没render

函数式组件

父子组件刷新的逻辑

  • 同class组件的区别?
    在父组件属性变更时,函数式组件会进行浅对比再判断是否需要渲染,
  • 那同加了memo的区别是啥呢?
    memo用于当组件接收到父组件的更新渲染通知时,进一步对属性进行浅比较来判断是否更新,如果没有memo,那么组件接收到来自父组件更新通知时则强行渲染

相关文件引用及推荐

相关文章

  • React生命周期及减少render次数

    React生命周期 环境:react16 常用生命周期的钩子分类后,分布3个阶段内 初始化阶段 - 组件创建阶段才...

  • React 生命周期

    React 生命周期 旧生命周期 挂载 constructor componentWillMount render...

  • pureComponent

    PureComponent是优化react应用程序最重要的方法,可以减少不必要的render次数,提高性能。 原理...

  • React 生命周期

    React 生命周期方法 我们接触较多的应该是 render()方法,其实这也是React的生命周期方法之一。还有...

  • react 性能优化

    减少render次数 使用PureComponent,默认实现了shouldComponentUpdate方法,对...

  • React生命周期小结

    react生命周期流程 1.初始化,首次render getDefaultProps()getDefaultPro...

  • react-native的组件生命周期

    react-native的组件生命周期 组件的相关方法 render 每个组件必须提供render方法。说该函数不...

  • React:State&生命周期

    State&生命周期 1.当 被传递给 ReactDOM.render() 时,React 调...

  • react 基础知识

    生命周期 旧 初始化阶段 由React.render 触发 -- 初次渲染 constructor() 构造函数...

  • React学习之前端开发性能优化

    1. 单个react组件性能优化 1.1 render里面尽量减少新建变量和bind函数的使用,尽量减少传递参数的...

网友评论

      本文标题:React生命周期及减少render次数

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