反应箭头功能仅接收初始状态

时间:2020-08-18 12:58:45

标签: reactjs arrow-functions use-state react-state

我正在按按钮设置计时器。我确实有一些状态在运行,但是在我的箭头函数backLunch中,我只收到了timerR的初始状态。

这里是代码;

export default function TimeTracker(props) {
  const [buttonLabel, setButtonLabel] = useState("start timer")
  const [buttonAction, setButtonAction] = useState()
  const [timerR, setTimerR] = useState(0)
  let interval

  const startTimer = () =>{
    const startTime = new Date;
    interval = setInterval(async() => {
      
      await setTimerR(new Date-startTime)
    },1000)

    setButtonLabel("lunch brake")
    setButtonAction(()=>lunchBrake)
  }
  const lunchBrake = () =>{
    window.clearInterval(interval);
    setButtonLabel("back from lunch")
    setButtonAction(()=>backLunch)
  }
  const backLunch = () =>{
    const backTime = new Date;
    const totalTime = backTime-timerR;
    interval = setInterval(async() => {
      
      await setTimerR(new Date-totalTime)
    },1000)

    setButtonLabel("back from lunch")
    setButtonAction(()=>goHome)
  }
  
  useEffect(() => {
    setButtonAction(()=> startTimer );
  }, [])



  return (
    <>
      <div className="tracker__header">
        <h2>Time Tracker</h2>
        <span className="tracker__time">
          <FontAwesomeIcon className="icon__default" icon={faClock}/> 
          {fortmatMilliTimer(timerR)}
        </span>
      </div>

      <div className="tracker__buttons">
        <Button type="attention" text={buttonLabel} action={buttonAction} />
        <Button type="default" text="input time" action={e => props.setModal("input")} />
      </div>
    </>
  );

我在backLunch函数中收到timerR = 0。

如何在调用timerR时获取它的实际状态?

1 个答案:

答案 0 :(得分:0)

尝试以下方法:-

const backLunch = () =>{
  const backTime = new Date;
  interval = setInterval(async() => {
    await setTimerR((latestTimerRVal) => {
      const totalTime = backTime - latestTimerRVal;
      return new Date-totalTime; // this will be set as new value ofr timerR
    })
  },1000)

  setButtonLabel("back from lunch")
  setButtonAction(()=>goHome)
}

setter函数可以将以最新状态值作为参数的arg函数用作参数。这可能会解决问题。

问题在这里setButtonAction(()=>lunchBrake)timerR的闭合值是0。因此是问题。