【问题标题】:Component doesn't update once the parents state is changed父状态更改后组件不会更新
【发布时间】:2023-03-29 19:57:01
【问题描述】:

我试图让一个计时器首先快速调用一个函数,然后放慢速度。我有一个 TimeInterval 状态,该状态会增加并作为道具传递给我的倒计时组件

<Countdown
      isActive={RandominatorRunning}
      target={() => NextSelection()}
      timeToChange={TimeInterval}
  />

倒计时组件

import React, { useEffect } from 'react';

const Countdown = ({ isActive, target, timeToChange }) => {


    useEffect(() => {
        let interval = null;
        if (isActive) {
            interval = setInterval(() => {
                target()
            }, timeToChange)
        } else if (!isActive) {
            clearInterval(interval)
        }
        return () => clearInterval(interval)
    }, [isActive])

    return null
}

export default Countdown;

我的 TimeInterval 状态正常工作,并且会随着 NextSelection() 的调用而增加。然而,这似乎并没有增加倒计时组件的间隔,并且 NextSelection() 总是以相同的速度被调用,而不是以改变状态的 TimeInterval 速度。为什么倒计时组件没有随着 TimeInterval 状态更新它的速度?

【问题讨论】:

标签: javascript reactjs react-native state react-props


【解决方案1】:

不肯定这是最好的解决方案,但我能够改变我的倒计时组件以获得预期的效果。

我将倒计时组件更改为在执行道具更新时变为非活动状态,然后在道具更新完成后立即恢复。

import React, { useEffect, useState } from 'react';

const Countdown = ({ isActive, target, timeToChange }) => {

    const [Active, setActive] = useState(isActive)

    const handleTimeExpire = async () => {
        await target()
        setActive(true)
    }

    useEffect(() => {
        let interval = null;
        if (Active) {
            interval = setInterval(() => {
                setActive(false)
                handleTimeExpire()
            }, timeToChange)
        } else if (!Active) {
            clearInterval(interval)
        }
        return () => clearInterval(interval)
    }, [Active])

    return null
}

export default Countdown;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 2019-07-12
    • 2021-07-17
    • 2021-07-07
    • 2018-11-03
    • 2016-10-02
    • 2019-12-12
    相关资源
    最近更新 更多