说来惭愧,准大四计算机专业学生党第一次写技术博客。
以前学东西没有记录的习惯总是容易忘记。
最近在看老师的教程学习React框架,想写点东西记录一下学习的过程。
若写的不好,各位大佬见谅了,欢迎指正。
什么是生命周期函数?
生命周期函数就是组件某一时刻会自动执行的函数。
React生命函数如下图所示分为四个部分
Initialzation: 初始化
Mounting: 组件被挂载
Updation: 组件被更新
Unmounting: 组件被移除
接下来我会对每个生命周期函数函数写测试用例:
父组件内:
//组件被挂载之前,自动执行
componentWillMount(){
console.log("componentWillMount");
}
//组件被挂载之后,自动执行
componentDidMount(){
console.log("componentDidMount");
}
//组件渲染到页面上的时候,自动执行
render(){
console.log("parent render");
}
//组件被更新前,自动执行
//返回值为true组件可被更新
//返回值为false组件不可被更新
shouldComponentUpdate(){
console.log("shouldComponentUpdate");
return true;
}
//组件被更新前,自动执行,但在shouldComponentUpdate之后
//如果shouldComponentUpdate为true,它才执行,否则不执行
componentWillUpdate(){
console.log("componentWillUpdate");
}
//组件更新完,自动执行
componentDidUpdate(){
console.log("componentDidUpdate");
}
子组件内:
//当一个组件从父组件接收参数时
//如果这个组件第一次存在父组件中,不执行
//如果这个组件之前已经存在父组件中,才会执行。
componentWillReceiveProps(){
console.log("child componentWillReceiveProps")
}
//当一个组件即将被从页面中剔除的时候,自动执行
componentWillUnmount(){
console.log("child componentWillUnmount")
}
好,接下来根据我之前所写好的React组件测试代码来看一下结果。