美文网首页
React生命周期

React生命周期

作者: 蛋黄肉 | 来源:发表于2017-09-25 21:56 被阅读24次

React生命周期

每个组件都有几个“生命周期方法”,您可以在此过程中的特定时间覆盖运行代码。前缀是will的方法在事情发生之前被调用,前缀的为did的方法在事情发生之后被调用。

  • Mounting 当创建组件的实例并将其插入到DOM中时,将调用这些方法:

    • constructor()
    • componentWillMount()
    • render()
    • componentDidMount()
  • Updating 更新可能是传入的参数或状态的改变引起的。当重新呈现组件时,将调用这些方法:

    • componentWillReceiveProps()
    • shouldComponentUpdate()
    • componentWillUpdate()
    • render()
    • componentDidUpdate()
  • Unmounting 当从DOM中删除组件时调用此方法:

    • componentWillUnmount()

我们将每个状态的方法归纳一下可能会方便我们的记忆

三个状态

  • Mounting:已插入真实 DOM
  • Updating:正在被重新渲染
  • Unmounting:已移出真实 DOM

五种方法

  • componentWillMount()
  • componentDidMount()
  • componentWillUpdate(object nextProps, object nextState)
  • componentDidUpdate(object prevProps, object prevState)
  • componentWillUnmount()

两种特殊状态

  • componentWillReceiveProps(object nextProps):已加载组件收到新的参数时调用
  • shouldComponentUpdate(object nextProps, object nextState):组件判断是否重新渲染时调用

那么我们插入节点的时候,组件都做了什么呢?

  • constructor()
    • 构造函数,是用来初始化这个组件的,可以让组件的state根据传入的props的值不同而不同,如果你的组件是一个静态的,就可以不适用这个函数,下面是官网的例子
      constructor(props) {
          super(props);
          this.state = {
              color: props.initialColor
          };
      }
      
    • 注意这里面代码的第二行到第五行只能在第一次初始化的时候调用,千万别指望这种写法能够让你时时的更新你的组件
  • componentWillMount()
    • 当你的组件要�插入DOM时立刻被调用,render()将在他的后面被调用
    • 这个方法�不会同步更新state
    • 这是唯一一个在服务器上调用的方法,�应该使用constructor代替这个方法
  • render()
    • 这个是必须出现在你的组件中的方法,也是我们最经常用的方法
    • 在调用的时候应该检查this.statethis.props并且返回一个元素
    • 在这个组件中,不要更改组件的状态,不要与�浏览器发生交互
    • 如果你什么也不想让任何元素插入DOM,请reture false或return null
  • componentDidMount()
    • 尽可能多的将网络请求写在这里
    • 此方法中的设置状态将触发重新渲染。

接下来是更新节点

  • componentWillReceiveProps()
    • 在组件接收到新的props前被调用,
  • shouldComponentUpdate()
  • componentWillUpdate()
  • render()
  • componentDidUpdate()
    //未完待续

相关文章

  • React概念图

    React概念图 React组件生命周期概念图 参考文档:React入门教程 组件生命周期React:组件生命周期...

  • React基础篇之组件的生命周期

    引出生命周期 react生命周期(旧) react生命周期(新) getSnapshotBeforeUpdate的...

  • React生命周期

    React v16.0前的生命周期 React v16.4+ 的生命周期图 React v16.9后这些生命周期钩...

  • React v16 生命周期

    React 16 生命周期 React 16.3 新增的生命周期方法 逐渐废弃的生命周期方法: 一般将生命周期分成...

  • 学习并实现react (4)

    实现生命周期 生命周期介绍 React 生命周期图 React 子组件在父组件下的生命周期流程 实现 compon...

  • React面试题 整理脑图

    react基础 React生命周期 react-router react进阶 react Hooks redux 其他

  • react/vue常见问题整理

    一、react 1. react生命周期 react 16生命周期相对于15的变化:componentWillMo...

  • React 组件生命周期

    组件生命周期 参考阅读: component-lifecycle react组件生命周期过程说明 react 组件...

  • 《深入React技术栈》学习笔记Ⅲ

    以下的生命周期都是在 React 15 的生命周期, React 16 的生命周期 API 已经发生变化。Reac...

  • React总结

    [toc] 1.React组件生命周期 1.1 生命周期图 组件的生命周期的图如下: 具体可参考React 组件生...

网友评论

      本文标题:React生命周期

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