我有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.
如何在生命周期方法中设置状态而不会出现这些错误?
答案 0 :(得分:2)
尽管这是一个古老的问题,但我会作答以供将来参考。
通过setState
使用setTimeout
(异步)时,必须记住清除componentWillUnmount
上的超时。
否则,您可能会遇到以下情况:在元素已卸装后调用setState
。
答案 1 :(得分:1)
如何在componentWillUpdate
上进行设置?这样,您就知道该组件已经安装。文档How to highlight a current menu item?
如果要设置初始状态,请在componentWillMount
中进行。
答案 2 :(得分:0)
您需要检查您的组件是否已安装。您可以在州内创建触发器mounted
,并在生命周期方法中对其进行管理。
constructor(props) {
super(props);
this.state = { mounted: false };
}
componentDidMount() {
this.setState({ mounted: true });
}
componentWillUnmount() {
this.setState({ mounted: false });
}
componentWillReceiveProps(nextProps){
if(this.props.totalVehicles !== nextProps.totalVehicles &&
this.state.mounted){
this.setState({animation: "cartCount"}, () => setTimeout(() =>
this.setState({animation: null}), 1000));
}
}
答案 3 :(得分:0)
代替使用状态“ mount”,请尝试使用实例变量“ mount”:
constructor(props) {
super(props);
this.mounted = false;
}
componentDidMount() {
this.mounted = true;
}
componentWillUnmount() {
this.mounted = false;
}
componentWillReceiveProps(nextProps){
if(this.props.totalVehicles !== nextProps.totalVehicles &&
this.mounted){
this.setState({animation: "cartCount"}, () => setTimeout(() =>
this.setState({animation: null}), 1000));
}
}