React 生命周期是 React 组件从创建到销毁的各个阶段。理解组件的生命周期可以帮助我们更好地控制组件的行为,优化性能。

生命周期方法

React 组件生命周期包括以下几种方法:

  • componentDidMount(): 组件挂载后调用。
  • componentDidUpdate(): 组件更新后调用。
  • componentWillUnmount(): 组件卸载前调用。
  • componentWillMount(): 组件挂载前调用(已弃用)。
  • componentWillUpdate(): 组件更新前调用(已弃用)。

示例

以下是一个简单的组件示例,展示了如何使用生命周期方法:

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  componentDidMount() {
    console.log('组件挂载完成');
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.state.count !== prevState.count) {
      console.log('组件状态更新');
    }
  }

  componentWillUnmount() {
    console.log('组件即将卸载');
  }

  handleClick = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>计数:{this.state.count}</p>
        <button onClick={this.handleClick}>增加计数</button>
      </div>
    );
  }
}

扩展阅读

更多关于 React 生命周期的信息,可以参考官方文档:React 生命周期

![React 生命周期图解](https://cloud-image.ullrai.com/q/React_Lifecycle Diagram/)