React的生命周期

46 阅读1分钟

React的生命周期方法三个主要的阶段:挂载(Mounting)、更新(Updating)和卸载(Unmounting)。

1. 挂载(Mounting)

挂载阶段发生在组件被实例化并插入DOM中时。

  • constructor():初始化React组件的状态
  • componentDidMount():组件渲染后,只调用一次。组件已成功渲染到DOM中,可以进行DOM相关的操作,例如:定时器或发送请求等。
class MyComponent extends React.Component {

constructor(props) {

super(props);

this.state = { value: 0 };

}

componentDidMount() {

// 初始化DOM相关的操作

}

render() {

return <div>{this.state.value}</div>;

}

}

2. 更新(Updating)

当组件的属性或状态发生变化时。

  • render():根据新的属性/状态渲染虚拟DOM,返回要渲染的元素。
render() { 
return <div>{this.state.count}</div>; 
}
  • componentDidUpdate():组件初始化时不调用,组件更新完成后会调用此方法,可以进行DOM相关的操作。
class MyComponent extends React.Component {

// ...

componentDidUpdate(prevProps, prevState) {

// 执行DOM相关的更新操作

}

// ...

}

3. 卸载(Unmount)

当组件从DOM中移除时

  • componentWillUnmount():组件即将被移除,可以在这里清理计时器,取消网络请求。
class MyComponent extends React.Component {

// ...

componentWillUnmount() {

// 清理工作,例如清除计时器

}

// ...

}