在生命周期方法React JS中设置状态

Bok*_*oky 5 reactjs

我有React生命周期方法如下:

componentWillReceiveProps(nextProps){
    if(this.props.totalVehicles !== nextProps.totalVehicles){
        this.setState({animation: "cartCount"}, () => setTimeout(() =>  this.setState({animation: null}), 1000));
    }
}
Run Code Online (Sandbox Code Playgroud)

但这给了我:

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.
Run Code Online (Sandbox Code Playgroud)

如何在生命周期方法中设置状态而不会出现这些错误?

jam*_*cia 1

将其设置为如何componentWillUpdate?这样,您就知道该组件已经安装。文档在这里

如果要设置初始状态,请在 中进行componentWillMount

更多生命周期方法在这里