【发布时间】:2018-06-30 21:30:58
【问题描述】:
我的 React 生命周期方法如下:
componentWillReceiveProps(nextProps){
if(this.props.totalVehicles !== nextProps.totalVehicles){
this.setState({animation: "cartCount"}, () => setTimeout(() => this.setState({animation: null}), 1000));
}
}
但这给了我:
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 Header component.
如何在生命周期方法中设置状态而不出现这些错误?
【问题讨论】:
-
理想情况下,您可以在
componentWillReceiveProps中设置状态,错误可能是因为您使用的是setTimeout。挂载完成后是设置状态,所以报错。 -
您是否在执行 setTimeout 之前以某种方式离开组件,您可能会尝试使用此解决方案 stackoverflow.com/questions/39767482/… 并仅在组件已安装时在 setTimeout 中使用 setState
-
@ShubhamKhatri 不。
-
否则您的代码似乎是正确的,我尝试对其进行演示,并且效果很好codesandbox.io/s/ymmp7vxw61
标签: reactjs