gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:37:09 24 4
gpt4 key购买 nike

我的 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.

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

最佳答案

虽然这是一个老问题,但我会回答它以供将来引用。

通过setTimeout使用setState(异步)时,您必须记住清除componentWillUnmount上的超时。否则,您可能会遇到在元素已卸载后调用 setState 的情况。

关于reactjs - 在 React JS 生命周期方法中设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48378402/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com