react入门(下)

react生命周期

1. 组件的三个生命周期状态:
* Mount:插入真实 DOM
* Update:被重新渲染
* Unmount:被移出真实 DOM
2. React 为每个状态都提供了两种勾子(hook)函数,will 函数在进入状态之前调用,did 函数在进入状态之后调用
* componentWillMount()
* componentDidMount() : 已插入真实DOM, 在render之后才会执行
* componentWillUpdate(object nextProps, object nextState)
* componentDidUpdate(object prevProps, object prevState)
* componentWillUnmount()
3. 生命周期流程:
1). 第一次初始化渲染显示: render()
* constructor(): 创建对象初始化state
constructor参数接受两个参数props,context
只要组件存在constructor,就必要要写super

* componentWillMount() : 将要插入回调
组件刚经历constructor,初始完数据
组件还未进入render,组件还未渲染完成,dom还未渲染

* render() : 用于插入虚拟DOM回调
render函数会插入jsx生成的dom结构,react会生成一份虚拟dom树,在每一次组件更新时,在此react会通过其diff算法比较更新前后的新旧DOM树,比较以后,找到最小的有差异的DOM节点,并重新渲染

* componentDidMount() : 已经插入回调
2). 每次更新state: this.setSate()
* componentWillUpdate() : 将要更新回调
* render() : 更新(重新渲染)
* componentDidUpdate() : 已经更新回调
3). 删除组件
* ReactDOM.unmountComponentAtNode(document.getElementById('example')) : 移除组件
* componentWillUnmount() : 组件将要被移除回调
4.注意:
* 一般会在componentDidMount()中: 开启监听, 发送ajax请求
* 可以在componentWillUnmount()做一些收尾工作: 停止监听组件,将要卸载时调用,一些事件监听和定时器需要在此时清除。
* componentWillReceiveProps
componentWillReceiveProps在接受父组件改变后的props需要重新渲染组件时用到的比较多


原文地址:https://www.cnblogs.com/ntbww93/p/9687217.html