实现思路
- 挂载阶段:使用
componentDidMount
生命周期方法,首次获取数据并缓存。
- 更新阶段:在
shouldComponentUpdate
中判断 props
或 state
是否变化,如果变化则重新获取数据。同时,使用 componentDidUpdate
生命周期方法,对比之前的数据与新获取的数据,只有当数据真正不同时才更新缓存。
- 卸载阶段:使用
componentWillUnmount
方法清理相关资源(如果有需要)。
关键代码片段
import React, { Component } from'react';
class DataDependentComponent extends Component {
constructor(props) {
super(props);
this.state = {
data: null,
cachedData: null
};
}
componentDidMount() {
this.fetchData();
}
componentDidUpdate(prevProps, prevState) {
if (prevProps.someProp!== this.props.someProp || prevState.someState!== this.state.someState) {
this.fetchData();
}
}
shouldComponentUpdate(nextProps, nextState) {
return nextProps.someProp!== this.props.someProp || nextState.someState!== this.state.someState;
}
componentWillUnmount() {
// 清理资源(如果有需要)
}
fetchData = async () => {
const newData = await this.getDataFromAPI();
if (newData!== this.state.cachedData) {
this.setState({
data: newData,
cachedData: newData
});
}
}
getDataFromAPI = () => {
// 模拟异步获取数据
return new Promise(resolve => {
setTimeout(() => {
resolve({ some: 'data' });
}, 1000);
});
}
render() {
return (
<div>
{this.state.data && <p>{JSON.stringify(this.state.data)}</p>}
</div>
);
}
}
export default DataDependentComponent;