首页 > 解决方案 > componentDidUpdate 中的更新变量失败

问题描述

我在我的视图中有一个弹出窗口,在弹出窗口中有一个倒数计时器。当倒数计时器具有 value1 时,我需要隐藏弹出窗口。这是我尝试过的。

componentDidUpdate() {
        if (this.state.count === 1) {
            clearInterval(this.intervalDuration);
            this.setState({popupvisible:false})
        }
    }

当计数等于 1 时出现错误,如下所示。

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

标签: react-native

解决方案


如果您正在设置状态变量,那么也可以在条件中添加该变量以避免重复更新。

componentDidUpdate() {
    if (this.state.count === 1) {
        clearInterval(this.intervalDuration);
        if(this.state.popupvisible){
        this.setState({popupvisible:false})}
    }
}

推荐阅读