1、
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 ServiceAddOrEdit component.
这个问题是说,我们发送了一个异步请求,但是在这个异步请求返回之前,组件可能就已经被卸载了,等数据回来再使用setState就会报出上面的警告。
解决方案:
componentWillUnmount方法,这个方法官方文档是这么写的,当这个组件被移除的时候,会调用这个函数。
If the Clock component is ever removed from the DOM, React calls the componentWillUnmount() lifecycle hook so the timer is stopped.
最终代码可以写为这样:
componentWillMount() {
this._isMounted = true;
getList().then((data) => {
if (this._isMounted) {
this.setState({data: data});
}
});
};
componentWillUnmount() {
this._isMounted = false;
};