React16.3版本之前的生命周期图示如上图,
React的生命周期分为:
1. initialization(初始化阶段)
- constructor钩子函数,可以设置局部状态数据state
2. Mounting(挂载阶段)
- componentWillMount(将要挂载)
- render(渲染)
- componentDidMount(挂载完成)
3. Updation(更新阶段)
通过改变props或者state数据来实现组件的更新
- props特有钩子函数:componentWillReceiveProps(组件将要接收参数)
16.3之后版本该函数被删去 - shouldComponentUpdate (判断组件是否需要更新)
shouldComponentUpdate返回一个布尔值 用于判断组件是否需要更新,默认返回true
在开发中如果需要对项目做性能优化可以针对此方法做处理
shouldComponentUpdate(p, s) {
console.log('判断组件是否需要更新');
console.log(p);
console.log(s);
console.log(this.state);
// if (s.childCount % 2 == 0) {
// return true;
// } else {
// return false;
// }
return true;
}
- componentWilUpdate (将要更新)
- render (渲染)
- componentDidUpdate(更新完成)
通过this.setState更改state数据
constructor(props){//初始化设置state数据
super(props)
// console.log(props)
this.state=({
movie:{
video:{
url:''
}
}
})
}
async componentDidMount(){//更新完成
const result =await movieDetail(query.id)//发送请求
this.setState({//更改state数据
movie:result.data.data.basic
})
}
4. Unmounting(挂载阶段)
- componentWillUnmount(组件将要卸载)清除定时器