reactjs – 在生命周期方法React JS中设置状态
发布时间:2020-12-15 05:04:20 所属栏目:百科 来源:网络整理
导读:我有React生命周期方法如下: componentWillReceiveProps(nextProps){ if(this.props.totalVehicles !== nextProps.totalVehicles){ this.setState({animation: "cartCount"},() = setTimeout(() = this.setState({animation: null}),1000)); }} 但这给了我
我有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的情况. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |