React生命周期
<pre><code>export default class demo extends React.Component{
//挂载过程:
constructor(props){
//数据的初始化,它接受两个参数:props和context,当想在函数内部使用这两个参数时,需使用super()传入这两个参数
super(props)
this.state = {}
}
componentWillMount(){
//在服务端渲染时使用,代表的过程是组件已经经历了constructor()初始化数据后,但是还未渲染DOM时
}
componentDidMount(){
//组件第一次渲染完成,此时dom节点已经生成,可以在这里调用ajax请求,返回数据setState后组件会重新渲染
}
componentWillUnmount(){
//此处完成组件的卸载和数据的销毁
}
//更新过程:
componentWillReceiveProps(nextProps){
//在接受父组件改变后的props需要重新渲染组件时用到的比较多,通过对比nextProps和this.props,将nextProps的state为当前组件的state,从而重新渲染组件
}
shouldComponentUpdate(nextProps,nextState){
//主要用于性能优化,父组件更新会导致所有子组件更新,在这里return false可以阻止不需要更新的子组件进行更新
}
componentWillUpdate(nextProps,nextState){
//类似componentWillMount
}
componentDidUpdate(prevProps,prevState){
//每次更新完成都会进入这里,第一次挂载只进入componentDidMount
}
render(){
//生成一份虚拟dom树,组件每次更新会比较新旧dom树,找到最小差异的dom节点重新渲染
return (
<div>demo</div>
)
}
}</code></pre>
<p>参考:<a href="https://www.jianshu.com/p/b331d0e4b398">https://www.jianshu.com/p/b331d0e4b398</a></p>