一、简介
React组件都要经历三个阶段:挂载、更新、卸载。每个阶段都包含 “生命周期方法”,重写这些方法,就可以在特定的阶段执行特殊操作。
二、生命周期图
三、class组件的3个生命周期方法
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
// 组件被挂载后调用
componentDidMount() {
}
// 组件更新渲染完后调用
componentDidUpdate() {
}
// 组件卸载后调用
componentWillUnmount() {
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}