![](/img/trans.png)
[英]Why is my state beeing updated before i call setState with React Hooks and how do i fix the disabled mouse pointer?
[英]How to access the updated state after setState method with react hooks?
单击按钮时,我想将 state 设置为selectedMealPlan ,将更新的 state 存储到localStorage并路由到另一个组件。
const [selectedMealPlan, setSelectedMealPlan] = useContext(
selectedMealPlanContext
);
const AddItem = (e: any) => {
setSelectedMealPlan((prev: any) => ({
...prev,
nutrients: {
newValue: "newValue",
},
}));
localStorage.setItem("mealplan", JSON.stringify(selectedMealPlan))
history.push("/home");
};
问题是 setState() 是异步的,我只能将旧的 state 存储到 localStorage,有没有办法可以访问最新的 state?
我会使用useEffect
来观察selectedMealPlan
的变化,当检测到时,调用setItem
:
const AddItem = (e: any) => {
setSelectedMealPlan((prev: any) => ({
...prev,
nutrients: {
newValue: "newValue",
},
}));
};
useEffect(() => {
localStorage.setItem("mealplan", JSON.stringify(selectedMealPlan))
history.push("/home");
}, [selectedMealPlan]);
您还可以将新的 state object 保存在setSelectedMealPlan
回调内的变量中,然后都使用它调用setItem
并将其返回给新的 state ,但这很奇怪。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.