React 生命周期是 React 组件从创建到销毁的过程。理解生命周期对于编写高效和可预测的组件至关重要。
创建阶段
当组件被创建时,以下生命周期方法会被调用:
constructor(props)
:初始化状态和绑定方法。componentDidMount()
:组件已挂载到 DOM 上,可以在此方法中获取 DOM 元素或发起网络请求。
class Example extends React.Component {
constructor(props) {
super(props);
this.state = { /* 初始化状态 */ };
}
componentDidMount() {
// 获取 DOM 元素或发起网络请求
}
render() {
return <div>{/* 渲染内容 */}</div>;
}
}
更新阶段
当组件的 props 或 state 发生变化时,以下生命周期方法会被调用:
componentWillReceiveProps(props)
:在组件接收到新的 props 之前调用。shouldComponentUpdate(nextProps, nextState)
:在组件更新之前调用,可以返回一个布尔值来决定是否更新组件。componentWillUpdate(nextProps, nextState)
:在组件更新之前调用。componentDidUpdate(prevProps, prevState)
:在组件更新之后调用。
class Example extends React.Component {
componentWillReceiveProps(nextProps) {
// 处理新的 props
}
shouldComponentUpdate(nextProps, nextState) {
// 根据条件返回 true 或 false
return true;
}
componentWillUpdate(nextProps, nextState) {
// 在组件更新之前做一些准备工作
}
componentDidUpdate(prevProps, prevState) {
// 在组件更新之后做一些清理工作
}
render() {
return <div>{/* 渲染内容 */}</div>;
}
}
销毁阶段
当组件不再需要时,以下生命周期方法会被调用:
componentWillUnmount()
:在组件卸载之前调用,可以在此方法中清理定时器、取消订阅等。
class Example extends React.Component {
componentWillUnmount() {
// 清理定时器、取消订阅等
}
render() {
return <div>{/* 渲染内容 */}</div>;
}
}
总结
React 生命周期为开发者提供了丰富的 API 来控制组件的行为。通过理解生命周期,我们可以更好地管理组件的状态和性能。