Props,state,与render和函数的关系
当组件的state或者props发生改变时,render函数会重新执行
当父组件的render函数被运行时,他的子组件的render都将被重新执行
生命周期函数:指在某一时刻会自动执行的函数。
render是一个生命周期函数,因为它在页面初次渲染的时候就会自动执行。
constructor也是一个生命周期函数,不过它属于es6语法。
Initialization:初始化时执行
Mounting:加载时执行
Updation:数据更新时执行
Unmounting:组件删除时执行
图中的函数都是生命周期函数,会在某一个时刻执行。
生命周期函数执行的时刻
Initialization
执行setup props and state 在constructor中去创建props和state。
Mounting
render函数中的返回内容就是页面加载出来的内容,在render函数加载之前会执行
componentWillMount函数,在render函数加载后会执行componentDidMount。
Updation
这部分可以看到有两个执行顺序,props和state。只是props多出了一个
componentWillReceiveProps函数。
相同部分
shouldComponentUpdate函数就是问你这个数据该不该改变,默认会返回true就是
改变数据,当不用改变数据时就自己返回false就行。
然后就执行componentWillUpdate->render->componentDidUpdate
这三个函数和组件挂载时的作用差不多,就是把页面重新渲染一下。
Unmounting
当一个组件在页面中移除的时候执行componentWillUnmount(移除之前)。
目前有特殊用途的生命周期函数
1.我们发送ajax请求一般都放在componentDidMount函数中来发送
2.上面没讲到的Updation中props中的componentWillReceiveProps函数。
这个组件作用于父子组件之间,条件是
大前提是子组件从父组件中接受参数,props变化时
(1)这个组件第一次存在于父组件中,不执行
(2)这个组件之前存在父组件中,才会执行
3.shouldComponentUpdate函数可以用来做性能优化,上面提到当父组件render
函数被运行时,他的子组件的render函数都将被重新执行,但是当子组件中接受的
参数没有发生改变时,就没有必要去重新执行子组件中的render函数。
shouldComponentUpdate(nextProps, nextState) {
if(nextProps.content !== this.props.content) {
return true;
}else {
return false;
}
}
shouldComponentUpdate可以接收两个参数,nextProps和nextState是接下来的props和state会变成什么样,只要发现接下来props和现在的props一样的话就会返回false,避免了不必要的渲染。节约性能。