如何解决反应箭头功能仅接收初始状态
我正在按按钮设置计时器。我确实有一些状态在运行,但是在我的箭头函数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时获取它的实际状态?解决方法
尝试以下方法:-
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。因此是问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。