React 组件的状态生命周期是理解组件如何与用户交互的关键。下面将介绍 React 组件的生命周期方法以及它们在组件生命周期中的角色。
生命周期方法
React 组件的生命周期方法包括以下几种:
componentDidMount()
: 组件挂载到 DOM 后调用。componentDidUpdate()
: 组件更新后调用。componentWillUnmount()
: 组件卸载前调用。componentWillMount()
: 组件挂载前调用,但在服务器端渲染期间不会调用。componentWillUpdate()
: 组件更新前调用,但在服务器端渲染期间不会调用。
生命周期图解
下面是一个简单的生命周期图解,展示了这些方法的调用顺序:
+-------------------+
| constructor() |
+--------+----------+
|
v
+--------+----------+
| componentDidMount() |
+--------+----------+
|
v
+--------+----------+
| componentDidUpdate() |
+--------+----------+
|
v
+--------+----------+
| componentWillUnmount() |
+-------------------+
实例
以下是一个简单的 React 组件示例,展示了生命周期方法的使用:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidMount() {
console.log('Component did mount');
}
componentDidUpdate(prevProps, prevState) {
console.log('Component did update');
}
componentWillUnmount() {
console.log('Component will unmount');
}
handleClick = () => {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.handleClick}>Increment</button>
</div>
);
}
}
扩展阅读
想要了解更多关于 React 状态生命周期的信息,可以阅读官方文档:React Lifecycle Documentation
React_Lifecycle