react 生命周期Mounting Updating Unmounting
挂载
定义:组件被创建并添加到DOM中的过程称为挂载。
理解:在挂载阶段,组件的构造函数(constructor)被调用,然后依次调用
rendercomponentDidMount
在
componentDidMount
更新
组件在接收props(属性)或state(状态)的时候更新。
具体:先render , 然后使用
componentDidUpdate函数。
卸载
就是:组件从DOM中移除
卸载的时候调用
componentWillUnmount函数(生命周期钩子函数)可以取消订阅,清除数据。
挂载,更新,卸载的例子:
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidMount() {
console.log('Component mounted');
}
componentDidUpdate(prevProps, prevState) {
console.log('Component updated');
if (prevState.count !== this.state.count) {
console.log('Count changed');
}
}
componentWillUnmount() {
console.log('Component will unmount');
}
incrementCount = () => {
this.setState(prevState => ({
count: prevState.count + 1
}));
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.incrementCount}>Increment</button>
</div>
);
}
}