在 componentDidMount
中,我使用 Redux
操作获取数据,例如:
componentDidMount() {
let parameter = some code;
this.props.getAction(parameter).then(r => {
if(r.type.endsWith('SUCCESS')){
this.setState({cList: r.payload.data.data})
}
}
}
然后,在 componentDidUpdate
中,当函数内的参数发生变化时,我需要再次获取数据(我正在使用 lodash
):
componentDidUpdate(prevProps, prevState){
if(!isEqual(this.props.parameter, prevProps.parameter){
let parameter = some code;
if(r.type.endsWith('SUCCESS')){
this.setState({cList: r.payload.data.data})
}
}
}
问题在于,如果componentDidUpdate
中的Promise
返回的结果在componentDidMount
中的Promise
之前,当我在组件中更改参数时,显示的数据是错误的;它仍然显示来自 componentDidMount
的数据,而不是来自 componentDidUpdate
中的新操作调用的数据。
我希望一切都清楚。
我怎样才能避免这种情况?谢谢。
最佳答案
你可以在你的组件中保留一个实例变量 lastRequestId
来跟踪哪个 promise 正在运行,就像这样:
class MyComponent extends Component {
constructor(props) {
super(props);
this.lastRequestId = null;
}
componentDidMount() {
let parameter = "some code";
this.lastRequestId = 'ON_MOUNT_REQUEST';
this.props.getAction(parameter).then(r => {
if(r.type.endsWith('SUCCESS') && this.lastRequestId === 'ON_MOUNT_REQUEST'){
this.setState({cList: r.payload.data.data})
}
})
}
componentDidUpdate(prevProps, prevState){
if(!isEqual(this.props.parameter, prevProps.parameter)) {
let parameter = "some code";
this.lastRequestId = 'ON_UPDATE_REQUEST';
this.props.getAction(parameter).then(r => {
if(r.type.endsWith('SUCCESS') && this.lastRequestId === 'ON_UPDATE_REQUEST'){
this.setState({cList: r.payload.data.data})
}
})
}
}
}
关于javascript - react : how to prevent api calls in ComponentDidMount and in ComponentDidUpdate override each other,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57871206/