我试图在组件更新后从服务器获取数据,但我无法做到这一点。据我了解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.