问题描述
我有一个相当简单的react容器组件,它试图在从componentDidMount调用的ajax回调中调用set状态.完整的错误是:
I've got a fairly simple react container component that attempts to call set state in an ajax callback called from componentDidMount. The full error is:
警告:setState(...):只能更新已安装或正在安装的组件.这通常意味着您在未安装的组件上调用了setState().这是无人值守.请检查UserListContainer组件的代码.
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the UserListContainer component.
console.log中的操作顺序为:
the order of operations from my console.log are:
render
child-render
componentDidMount
ajax-data
[Big ol Error Message]
我开始使用async/await,但是当我收到错误消息时,我返回了具有相同结果的回调.这是相关代码:
I started out using async/await but when I received the error I went back to callbacks with the same result. This is the relevant code:
export class UserListContainer extends React.Component<any, any>
{
constructor() {
super();
this.state = {
users: [], request: {}
};
}
//componentDidMount = async () => {
componentWillMount = () => {
console.log('componentWillMount');
//var response: Models.IUserQueryResponse = await Api.UserList.get(this.state.request);
Api.UserList.get(this.state.request).then((response) => {
console.log('ajax-data');
if (response.isOk) {
this.setState({ users: response.data, request: response.state });
}
});
}
render() {
console.log('render');
return <UserList
request={this.state.request}
users={this.state.users}
onEditClick={this.edit}
onRefresh={this.refresh}
/>;
}
任何帮助将不胜感激.
推荐答案
您无法在componentWillMount中设置状态,因为您的组件可能处于过渡状态./docs/react-component.html#componentwillmount"rel =" nofollow noreferrer>也不会触发重新渲染.使用componentWillReceiveProps或componentDidUpdate.
you cannot set state in componentWillMount because your component could be in a transitioning state.. also it will not trigger a re-rendering. Either use componentWillReceiveProps or componentDidUpdate.
现在,除了您的问题外,您还正在从API请求的回调中调用setState.而问题在于您可能已经卸载了该组件,并且不再想要setState了.
Now that aside your issue is that you are calling setState in the callback from an API request. and the issue with that is you probably have unmounted that component and dont want to setState anymore.
您可以使用一个简单的标志来解决此问题
you can fix this with a simple flag
constructor() {
super();
this.state = {
users: [], request: {}
};
this.isMounted = false;
}
componentDidMount(){
this.isMounted = true
}
componentWillUnmount(){
this.isMounted = false;
}
然后在您的api请求中执行此操作.
then in your api request you would do this.
Api.UserList.get(this.state.request).then((response) => {
console.log('ajax-data');
if (response.isOk && this.isMounted) {
this.setState({ users: response.data, request: response.state });
}
});
这篇关于在Ajax回调中设置状态会引发错误:警告:setState(...):只能更新已安装或正在安装的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!