阵营:的setState只能更新安装或安装组件
问题描述:
我需要在我的组件超时内的setState,所以我这样做:阵营:的setState只能更新安装或安装组件
componentDidMount() {
this.timeouts.push(setTimeout(() => {
this.setState({ text: 2 });
}, 4000));
}
componentWillUnmount() {
this.timeouts = [];
}
但我发现了这个错误:
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.
我在做什么错?
答
更改您的componentWillUnmount
以正确清除超时。您需要使用clearTimeout
清除超时而不是清空数组。
componentDidMount() {
this.timeouts.push(setTimeout(() => {
this.setState({ text: 2 });
}, 4000));
}
clearTimeouts: function() {
this.timeouts.forEach(clearTimeout);
}
componentWillUnmount() {
this.clearTimeouts();
}
致电前的setState您的组件将被安装,但您的组件没有安装该组件已安装后 –
@IhorSkliar componentDidMount被调用,在componentDidMount功能,所以设置状态不会是一个问题 –
@IhorSkliar我” m使用内部componentDidMount,因此它被挂载。 –