Mat*_*ima 2 javascript components reactjs
我的组件中需要一个超时内的setState,所以我这样做了:
componentDidMount() {
this.timeouts.push(setTimeout(() => {
this.setState({ text: 2 });
}, 4000));
}
componentWillUnmount() {
this.timeouts = [];
}
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.
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
更改您componentWillUnmount以正确清除超时.您需要使用clearTimeout清除超时而不是清空数组.
componentDidMount() {
this.timeouts.push(setTimeout(() => {
this.setState({ text: 2 });
}, 4000));
}
clearTimeouts: function() {
this.timeouts.forEach(clearTimeout);
}
componentWillUnmount() {
this.clearTimeouts();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6513 次 |
| 最近记录: |