[英]How to get the correct state in an useEffect hook, after another useEffect hook modifies the same state?
我有两个useEffect
钩子,它们都将在startTime/endTime
state 更改时运行。
useEffect(() => {
if (selectedProduct) {
fetch(...)
.then(res => res.json())
.then(res => setMyState(res.data));
}
}, [selectedProduct, startTime, endTime]);
useEffect(() => {
if(selectedStep){
console.log(myState); //this runs twice, once for the old state and once for the new state, after above useEffect's setState is complete
}
}, [selectedStep, startTime, endTime, myState]);
我从环顾四周了解到这可能是因为 React 进行了某种批处理以提高性能,因此setState
本质上是异步的。 此外, fetch
调用也将是异步的,因此设置新的 state 需要时间。
根据我的搜索,我看到使用setState
class based
React 组件有a callback
,但由于我使用的是钩子,我不知道该怎么做。 我可以在第一个中移动第二个useEffect
代码,但这需要一些丑陋if-else
条件,因为我需要检查selectedStep
是否没有改变,然后我可以直接使用res.data
。
有没有更好的方法来做到这一点?
这不是批量操作或类似的东西,它只是它的工作原理:当startTime
或endTime
发生变化时,每个钩子都会被执行,并且由于第一个更改myState
,您的第二个会再次被调用以进行该更改。
几个选项给你
按照您的描述组合钩子,即使它涉及条件逻辑。
根据您对myState
所做的事情,您可以让第二个钩子使用setMyState
的回调形式,它接收当前的 state 值作为参数。
(如果可能)在您的第二个useEffect
中删除对其他 state 项目的依赖,以便它仅在myState
更改时执行
尽管你说它会涉及一些if
/ else
,但如果你不能做#3,我会倾向于#1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.