componentDidMount
- 适合操作:在此处进行需要访问DOM的操作,如初始化第三方库(例如地图库、图表库等依赖DOM结构进行渲染的库),发起网络请求获取数据来更新组件状态。因为此时组件已经挂载到DOM树中,确保操作的安全性。
- 举例:
import React, { Component } from 'react';
class DataComponent extends Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount() {
fetch('https://example.com/api/data')
.then(response => response.json())
.then(data => this.setState({ data }));
}
render() {
return (
<div>
{this.state.data.map(item => (
<p key={item.id}>{item.name}</p>
))}
</div>
);
}
}
export default DataComponent;
componentDidUpdate
- 适合操作:当组件更新后,在此处对比前后的props或state,根据变化进行相应操作,如更新DOM(如果不是由React直接管理的部分),进行副作用操作(如重新计算一些依赖于props或state变化的值),或者在某些条件满足时再次发起网络请求。
- 举例:
import React, { Component } from 'react';
class CounterComponent extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidUpdate(prevProps, prevState) {
if (prevState.count!== this.state.count) {
console.log('The count has changed, you can perform additional actions here.');
}
}
handleIncrement = () => {
this.setState(prevState => ({
count: prevState.count + 1
}));
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.handleIncrement}>Increment</button>
</div>
);
}
}
export default CounterComponent;
componentWillUnmount
- 适合操作:清理在
componentDidMount
和componentDidUpdate
中创建的副作用,如取消网络请求(防止在组件卸载后响应回来仍然尝试更新已不存在的组件状态),清除定时器,解绑事件监听器等,避免内存泄漏。
- 举例:
import React, { Component } from 'react';
class TimerComponent extends Component {
constructor(props) {
super(props);
this.state = {
time: 0
};
this.timer = null;
}
componentDidMount() {
this.timer = setInterval(() => {
this.setState(prevState => ({
time: prevState.time + 1
}));
}, 1000);
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
return (
<div>
<p>Time elapsed: {this.state.time} seconds</p>
</div>
);
}
}
export default TimerComponent;