我试图在组件更新后从服务器获取数据,但我无法做到这一点。据我了解,当组件即将被销毁时,会调用 componentWillUnmount
,但我永远不需要销毁它,所以它对我来说毫无用处。对此有什么解决方案?我什么时候应该设置状态?
async componentDidUpdate(prevProps, prevState) {
if (this.props.subject.length && prevProps.subject !== this.props.subject) {
let result = await this.getGrades({
student: this.props.id,
subject: this.props.subject
});
this.setState({
subject: this.props.subject,
grades: result
});
}
}
async getGrades(params) {
let response, body;
if (params['subject'].length) {
response = await fetch(apiRequestString.gradesBySubject(params));
body = await response.json();
} else {
response = await fetch(apiRequestString.grades(params));
body = await response.json();
}
if (response.status !== 200) throw Error(body.message);
return body;
}
完整错误:
Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op,
but it indicates a memory leak in your application. To fix, cancel all subscriptions and
asynchronous tasks in the componentWillUnmount method.
最佳答案
我在本例中使用的常见模式类似于
componentWillUnmount() {
this.isCancelled = true;
}
然后在等待异步函数解析的代码中,您可以在设置状态之前添加检查:
async componentDidUpdate(prevProps, prevState) {
if (this.props.subject.length && prevProps.subject !== this.props.subject) {
let result = await this.getGrades({
student: this.props.id,
subject: this.props.subject
});
!this.isCancelled && this.setState({
subject: this.props.subject,
grades: result
});
}
}
这将停止未安装/卸载组件上的任何状态设置
关于javascript - 无法对已卸载的组件调用 setState(或forceUpdate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50428842/