首页 > 解决方案 > 仅接收初始状态的反应箭头函数

问题描述

我正在做一个按钮设置的计时器。我确实有一些状态正在运行,但是在我的箭头函数 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 的实际状态?

标签: reactjsarrow-functionsuse-statereact-state

解决方案


尝试以下操作:-

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)。这里的闭包值为timerR0。因此问题。


推荐阅读