所有带will 的生命周期钩子都要加上UNSAFE_ 除了componentWillUnmount
1.组件挂载阶段
1. 先执行构造器 constructor
2.再执行 componentWillMount (组件将要挂载)
3.初始化渲染阶段 render
4.再执行componentDidMount (组件完成挂载)
// 构造器
constructor(props) {
console.log('构造器', 'constructor');
super(props);
}
componentWillMount() {
console.log("组件将要挂载", "componentWillMount");
}
// 组件挂完成挂载
componentDidMount() {
console.log("组件完成挂载", "componentDidMount");
}
// 初始化渲染,状态更新后
render() {
console.log("渲染", "render");
return (
<div id="hahah"></div>
)
}
2.组件更新阶段 当需要触发更新时
1.shouldComponentUpdate()
当调用setState方法后 会触发这个函数 用于判断是否需要更新 如果不写默认返回true 如果返回false 则不会更新
2.componentWillUpdate() 组件将要更新
3.render() 渲染更新
4.componentDidUpdate() 组件更新完成
// 当调用setState方法后 会触发这个函数 用于判断是否需要更新 如果不写默认返回true 如果返回false 则不会更新
shouldComponentUpdate() {
console.log("组件是否应该更新", "shouldComponentUpdate");
return true;
}
// 组件将要更新
componentWillUpdate() {
console.log("组件将要更新", "componentWillUpdate");
}
// 组件更新完成
componentDidUpdate() {
console.log("组件更新完成", "componentDidUpdate");
}
// 初始化渲染,状态更新后
render() {
console.log("渲染", "render");
return (
<div id="hahah">
<div>{this.state.num}</div>
<button onClick={this.death}>哈哈了</button>
</div>
)
}
3. 不更改状态数据强制更新 跳过shouldComponentUpdate
render() {
console.log("渲染", "render");
return (
<div id="hahah">
<button onClick={this.fff}>不更改任何状态中的数据,强制更新</button>
</div>
)
}
fff = () => {
this.forceUpdate();
}
4.父子组件生命周期执行顺序
先执行父组件挂载 => 父组件render => 子组件挂载 =>子组件render => 子组件挂载完成 => 父组件挂载完成
父组件
constructor(props) {
console.log('父组件构造器', 'constructor');
super(props)
}
componentWillMount() {
console.log("父组件将要挂载", "componentWillMount");
}
// 组件挂完成挂载
componentDidMount() {
console.log("父组件完成挂载", "componentDidMount");
}
render() {
console.log("父组件渲染", "render");
return (
<div>
<Dome1 />
</div>
)
}
子组件
// 构造器
constructor(props) {
console.log('子组件构造器', 'constructor');
super(props)
}
componentWillMount() {
console.log("子组件将要挂载", "componentWillMount");
}
// 组件挂完成挂载
componentDidMount() {
console.log("子组件完成挂载", "componentDidMount");
}
// 初始化渲染,状态更新后
render() {
console.log("子组件渲染", "render");
return (
<div id="hahah"></div>
)
}
5. 组件将要被卸载
componentWillUnmount() {
console.log("子组件被卸载", "componentWillUnmount");
}