在间隔中使用状态时更新状态时出现问题

时间:2020-04-02 23:15:30

标签: javascript reactjs react-native react-hooks setinterval

我正在构建一个React Native应用,并试图创建一个计时器。计时器使用setInterval在前台正常运行,并更新保留秒数的状态位,并每秒钟减少一次。当应用程序后台运行时,将捕获并存储日期。当活动状态再次变为活动状态时,我正在尝试计算两个日期之间的时差,然后更新状态以反映该时差,以便向用户显示计时器在后台运行。

我遇到了一个问题,即计时器运行时状态没有更新。

const home = () => {

  const WORK_SECONDS = 1500; //1500
  const SHORT_REST_SECONDS = 300; //300
  const LONG_REST_SECONDS = 900; //900
  const ACTIVE_COLOR = '#009688';
  const PAUSED_COLOR = '#00695C';
  const ADD_TIME = 60;
  const NOTIFICATION_TITLE = "Time's up!";
  const NOTIFICATION_BODY = "Finished!";

  const [timer, setTimer] = useState({seconds: WORK_SECONDS, timeCap: WORK_SECONDS });
  const [isActive, setIsActive] = useState(false);
  const [timerColor, setTimerColor] = useState(ACTIVE_COLOR);
  const [sessionCycle, setSessionCycle] = useState([]);
  let time = 0;

  const toggle = () => {
    if (sessionCycle.length == 8) setSessionCycle([]);
    setIsActive(!isActive);
    setTimerColor((timerColor == ACTIVE_COLOR && timer.seconds != timer.timeCap) ? PAUSED_COLOR : ACTIVE_COLOR);
  }

  const reset = () => {
    setTimer({...timer, seconds: timer.timeCap});
    setIsActive(false);
  }

    useEffect(() => {
        AppState.addEventListener('change', handleChange);  
        return () => {
          AppState.removeEventListener('change', handleChange);  
        }
      }, []);

      const handleChange = (newState) => {
        if (newState === "active") {
          let resumeTime = moment(new Date());
          let exitTime = moment(time);
          let duration = moment.duration(resumeTime.diff(exitTime, 'seconds'));
          let diff = duration.asSeconds() * 1000;
          console.log("Attempting to substract - " + diff);
          console.log(timer.seconds + " from appstate");
          setTimer({...timer, seconds: timer.seconds - diff})
          console.log(timer.seconds + " after subtraction");
        }
        else if (newState == "background") {
          time = new Date();
        }
      }

      useEffect(() => {
        let interval = null;
        if (isActive) {
          if (timer.seconds == 0) {
            //sendNotification(); 
            // TODO: Add +1 to pomo total after finishing work session
            updateSessionCycle("forward");  
            clearInterval(interval);
            toggle();
          }
          interval = setInterval(() => {
            console.log(timer.seconds);
            setTimer({...timer, seconds: timer.seconds - 1});
          }, 1000);
        } else if (!isActive && timer.seconds !== 0) {
          clearInterval(interval);
        } 
        return () => clearInterval(interval);
      }, [isActive, timer.seconds]);

      const addTime = () => {
        if (timer.seconds > timer.timeCap - 60) {
          setTimer({...timer, seconds: timer.timeCap})
        } else {
          setTimer({...timer, seconds: timer.seconds + ADD_TIME});
        }
      }

    return (
        <View style={styles.chart}>
            <ProgressCircle
              percent={ (timer.seconds / timer.timeCap) * 100 }
              radius={Math.ceil(Dimensions.get('window').height / 6)}
              borderWidth={Math.ceil(Dimensions.get('window').height / 30)}
              color={timerColor}
              shadowColor="#212121"
              bgColor="#303030"
            >
              <Text style={{ color: '#FFF', fontSize: 50 }}>{moment("2015-01-01").startOf('day').seconds(timer.seconds).format('m:ss')}</Text>
              <Text style={{ color: '#9E9E9E', fontSize: 20 }}>{(timer.timeCap == WORK_SECONDS) ? "Work Session" : "Break"}</Text>
            </ProgressCircle>
        </View>
    );
}

1 个答案:

答案 0 :(得分:1)

我怀疑您的问题是您在对setTimer的呼叫中使用了过时状态。在useEffect中,您正在创建一个setInterval函数,该函数在函数闭包中引用timer。每次调用setInterval函数时,您将获得相同的timer变量,因此调用:

setTimer({...timer, seconds: timer.seconds - 1});

...将在创建间隔时将seconds的持续时间设置为比timer.seconds的值小1秒。

幸运的是,有一个简单的解决方法:

setTimer(timer => ({...timer, seconds: timer.seconds - 1}));

这将在每次执行更新之前获取最新的timer状态。