reactjs - 仅接收初始状态的反应箭头函数
问题描述
我正在做一个按钮设置的计时器。我确实有一些状态正在运行,但是在我的箭头函数 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。因此问题。
推荐阅读
- ios - 如何使用 swift 解析来自具有 2 个 CollectionViews 的 UIViewController 的数据
- spring - 我在eclipse中创建项目后,包名没有正确生成
- python - 无法在 Azure Databricks 上使用 UDF 解压缩流数据 - Python
- c# - 外部子网 PC 中 SQL Server 中的只读操作
- python - 为什么 django 表单输入没有保存在数据库中?
- php - 如果变量为空白/空,如何结束 PHP 进程
- python - 尝试从主机连接到 docker 容器内的 python 套接字
- r - 外部存储器上的功能子集
- r - dplyr 中的 Mutate_if 或 mutate_at 与日期
- jestjs - 为什么我收到“测试完成后无法登录?”