React 生命周期图:
1 组件的三个生命周期状态
Mount:插入真实的DOM
Update:被重新渲染
Unmount:被移出真实DOM
2 React为每个状态都提供了两种勾子(回调)函数,will函数在进入状态之前调用,did函数在进入状态之后调用
componentWillMount()
componentDidMount():已插入真实DOM,在render之后才会执行
componentWillUpdate(object nextProps,object nextState)
componentDidUpdate(object prevProps,object prevState)
componentWillUmount()
3 生命周期流程:
1 第一次初始化渲染显示:render()
constructor()创建对象初始化state
componentWillMount():将要插入回调
render() 用于插入虚拟Dom回调
componentDidMount() :已经插入回调
2 每次更新state:this.setState()
componentWillUpdate():将要更新回调
render() 用于插入虚拟Dom回调
componentDidUpdate() :已经更新回调
3删除组件
ReactDOM.unmountComponentAtNode(document.getElementById("example"));移除组件
4注意:
一般会在componentDidMount()中开监听,发送ajax请求
可在componentWillUmount()中进行一些收尾工作
明哥理解:
你打开一个页面,首先页面中一定会有最原始的数据,会自动调用componentWillMount方法,之后显示一个加载中的小动画。这实际上已经第一次调用render方法了,然后向服务器发送ajax请求获取数据,这里就会调用componentDidMount方法。
紧接着将ajax得到的数据更新到state中,这时候就会调用componentWillUpdate方法。之后更新页面(调用render方法)render方法之后就是componentDidUpdate方法
至于我们为什么不在render方法中发送ajax请求呢?是因为render方法会多次调用
总之mount 方法只会在页面打开的时候调用一下, Update方法则是在state发生变化之后就会调用。
字体变色
虚拟DOM+DOM diff算法:最小化页面重绘验证
下图所示代码一个组件中有一个输入框和一段时间,时间不停的变化,但是输入框内容却不发生变化,说明了react更新dom的最小化页面重绘