创建倒数计时器并使用Redux状态的数据时获得最大更新

时间:2020-07-22 06:33:13

标签: javascript reactjs momentjs

你们可以帮我吗?我想渲染我的倒数计时器HH:MM:SS。但是,我的数据处于状态。我的setInterval正常工作,但是当我尝试添加setState并传递数据进行渲染时,出现了错误。 Unhandled Rejection (Error): 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.

另外,这是我的代码:

componentDidMount() {
        this.props.dispatch(questActions.getAll());
        this.props.dispatch(userActions.getAll(1, 100000));
        this.getTimeRemaining();

        this.interval = setInterval(() => {
                this.getTimeRemaining();
        }, 1000)
    }

    componentWillUnmount() {
        clearInterval(this.interval)
    }

    getTimeRemaining() {
        const { quests } = this.props || {}
        const questLists = quests?.items?.items;
        let today = moment();
    
        if (typeof questLists !== 'undefined') {
            questLists.forEach(questTimer => {
                let currentDate = today;
                let expiredDate = moment(questTimer.expiresAt);
                let timeRemaining = duration(expiredDate.diff(currentDate))

                let hours = timeRemaining.hours();
                let minutes = timeRemaining.minutes();
                let seconds = timeRemaining.seconds();

                //Adding to array to render display
                questTimer.hours = hours;
                questTimer.minutes = minutes;
                questTimer.seconds = seconds;

                this.setState({
                    hours,
                    minutes,
                    seconds
                })
                
            })
        }
    }

1 个答案:

答案 0 :(得分:0)

您有一个无限循环。当组件在几小时,几分钟或几秒钟内更新时,您可能正在做一些事情。另外,您每隔一秒钟调用一次setState函数。您确定要呼叫setInterval吗?每秒连接到redux存储进行调度的目的是什么?也许setTimeout就足够了吗?

旁注: 如果redux存储中有更新,则无需调度即可获取其价值。也可以将其作为prop传递到您的组件,并且组件将自行更新。