React 状态与生命周期是 React 框架中非常重要的概念。下面将详细介绍它们的作用和使用方法。
状态(State)
状态是组件内部可变的数据。React 组件的状态通常用于响应事件处理函数。
- 使用
setState
方法更新状态。 - 状态的更新是异步的。
- 状态的更新可以触发组件的重新渲染。
生命周期
生命周期是组件从创建到销毁的过程。React 组件的生命周期包括以下几个阶段:
- 挂载(Mounting):
componentWillMount
:组件挂载之前调用。render
:组件挂载时调用,返回组件的 JSX 结构。componentDidMount
:组件挂载之后调用。
- 更新(Updating):
componentWillUpdate
:组件更新之前调用。render
:组件更新时调用,返回组件的 JSX 结构。componentDidUpdate
:组件更新之后调用。
- 卸载(Unmounting):
componentWillUnmount
:组件卸载之前调用。

实例
以下是一个简单的 React 组件示例,展示了状态和生命周期的使用:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
componentDidMount() {
console.log('组件已挂载');
}
componentDidUpdate(prevProps, prevState) {
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>
);
}
}
ReactDOM.render(<Counter />, document.getElementById('root'));
更多关于 React 的信息,请访问React 官方文档。