您的位置:首页 > Web前端 > React

React生命周期函数

2019-04-25 20:53 363 查看

React组件并不是真正的DOM,而是会生成虚拟DOM,虚拟DOM会经历一个创建、更新、删除的过程

什么是生命周期函数?

生命周期函数(钩子函数)通俗的说就是在某一时刻会被自动调用执行的函数。

react 的生命周期函数

下图是react组件加载的过程,注意箭头颜色

子组件会随着父组件的更新而更新
两种刚更新方式:
this.setState()    //主动更新
this.forceState()   //强制更新

生命周期函数

//加载
componentWillMount() {
console.log('组件将要加载: componentWillMount')
}
componentDidMount() {
console.log('组件已经加载:componentDidMount')
}
//更新生命周期,更新时调用
componentWillReceiveProps() {
//父组件更新时会调用
console.log('组件将要接收参数 :componentWillReceiveProps')

}
shouldComponentUpdate(nextProps,nextState) {//生命周期函数传参
console.log('组件要更新吗 :shouldComponentUpdate')
console.log(nextState) 下一个状态

}
}
componentWillUpdate() {
console.log('组件将要更新:componentWillUpdate')
}
componentDidUpdate() {
console.log('组件已经更新完毕:componentDidUpdate')
}
//卸载
componentWillUnmount() {
console.log('组件将要卸载:componentWillUnmount')

}
render() {
console.log('render 执行')
return (
<div style={{ border: 'solid green 1px' }}>Life
<br></br>
{/* this.setState 主动更新 */}
{/* this.forceUpdate 强制更新 */}
<button type="button" onClick={() => this.setState({})}>主动更新</button>
<button type="button" onClick={() => this.forceUpdate()}>强制更新</button>
</div>
)
}

React 17生命周期函数

新的生命周期函数对含有will的三个函数做了修改,
替换为了static getDerivedStateFromProps()

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: