react 中的生命周期是指,在某一个时刻组件会自动调用执行的函数。
constructor
此函数会在组件创建的时候调用,初始化整个 component,只会执行一次。componentWillMount
即将废弃
此函数会在组件挂载前触发。componentsDidMounte
组件在挂载完成后触发,只会执行一次。shouldComponentUpdate
组件在更新前触发,需要返回一个Boolean
结果,根据结果触发是否更新组件。componentWillUpdate
即将废弃
组件更新前shouldComponentUpdate
且返回true
后 触发componentDisUpdate
组件更新后执行componentWillUnmount
组件在被卸载前触发
class MyComponent extends Component {
constructor(props) {
super(props)
console.log('组件初始化执行函数');
}
componentWillMount() {
console.log('组件挂载前');
}
render() {
console.log('组件挂载组件');
}
componentDidMount() {
console.log('组件挂载完成');
}
shouldComponentUpdate(){
console.log('组件更新前');
return true;
}
componentWillUnmount(){
console.log('组件在卸载前触发')
}
}
在这里,我们可以用 sholdComponentUpdate
来控制组件的刷新,来提高程序的性能
shouldComponentUpdate(prevProp,state){
console.log('组件更新前');
return prevProp.content !== this.props.content;
}
这样就可以在组件更新之前阻止组件的更新。