好的!我给你写一个详尽的 React 类组件生命周期示例,里面涵盖主要的生命周期函数和它们的作用,还会有实际的操作(比如数据请求、状态更新、清理等),方便程序员理解和应用。
import React from 'react';
class LifecycleDemo extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
data: null,
loading: false,
error: null,
};
console.log('constructor: 初始化状态和绑定事件');
}
// 1. 挂载阶段:组件即将挂载,render前调用
static getDerivedStateFromProps(nextProps, prevState) {
console.log('getDerivedStateFromProps: 根据props更新state(静态方法,无this)');
// 例如,基于props某值调整state
if (nextProps.reset && prevState.count !== 0) {
return { count: 0 };
}
return null;
}
// 2. 挂载阶段:render后调用,适合操作DOM或异步请求
componentDidMount() {
console.log('componentDidMount: 组件挂载完成,适合数据请求