生命周期函数指: 在某一个时刻会自动执行的函数
图解:
//组件即将挂载到页面上的时候被执行的方法(组件第一次挂载的时候执行)
componentWillMount(){
console.log('componentWillMount');
}
//页面渲染到页面上的时候执行
render(){
console.log('render');
return <div></div>
}
//组件被挂载到页面上之后,被执行的方法(组件第一次挂载的时候执行)
componentDidMount(){
//一般情况下载该函数下进行 ajax 请求来获取数据 (axios、浏览器内置的 window.fetch())
/*
axios.get("接口").then(
() => {}
).catch(
() => {}
);
*/
console.log('componentDidMount');
}
/*
满足条件后执行
1.一个组件要从父组件接受参数
2.如果这个组件第一次存在于父组件中,则不会执行
3.如果这个组件已经存在于父组件中,才会执行
*/
componentWillReceiveProps(){
console.log('componentWillReceiveProps');
}
//组件更新之前会被执行的函数 可以通过该钩子函数来进行性能的优化
//参考: https://zh-hans.reactjs.org/docs/optimizing-performance.html
shouldComponentUpdate(){
console.log('shouldComponentUpdate');
return true; //需要返回一个Boolean类型,true表示更新
}
//组件更新前执行,但在shouldComponentUpdate之后,当其返回 false 时,不在往下执行
componentWillUpdate(){
console.log('componentWillUpdate');
}
//组件更新之后会被执行
componentDidUpdate(){
console.log('componentDidUpdate');
}
//当组件即将被从页面中剔除出去的时候回被执行
componentWillUnmount(){
console.log('componentWillUnmount');
}