[英]can someone explain to me how the async works in this scenario of useEffect?
我在孩子中有一个 onClick 事件:
onClick={()=>{ //2. an image is clicked, and the choice is added to the choiceOrder state, and then a jsonupdate is called -- 3. in ChooseBy.js
//onclick, add or remove the choice
choosebyprops.setChoiceOrder(choiceOrder => {
if (choiceOrder.includes(attrprops.attrChoice)) {
const choiceIndex = choiceOrder.findIndex(attrprops.attrChoice);
choosebyprops.setJsonList((_, i) => i !== choiceIndex+1)
return choiceOrder.filter(list => list !== attrprops.attrChoice);
} else {
const newList = [...choiceOrder, attrprops.attrChoice];
return newList
}
});
attrprops.setSelectedAttr( selectedAttr=>(selectedAttr!==attr ? attr : null) );
}}
点击之后,我需要一个列表来更新:
useEffect(()=>{
if(selectedAttr==null){
publishprops.setBuysideChoice( buysideChoice => ({'car_option':buysideChoice['car_option'],'zip_code':buysideChoice['zip_code']}) );
publishprops.setAttrNumber(2);
}
else {
publishprops.setBuysideChoice( buysideChoice => ({...buysideChoice,"body_type": selectedAttr}) );
publishprops.setAttrNumber(4);
};
},[selectedAttr])
useEffect(()=>{
const choiceOrder = choosebyprops.choiceOrder;
if (choiceOrder.includes(attrChoice) && choiceOrder[choiceOrder.length-1]==attrChoice) {
console.log('this json1',choosebyprops.jsonList)
choosebyprops.setJsonList(jsonList => [...jsonList, UpdateJson(allprops)]); //delayed
}
},[choosebyprops.choiceOrder])
但是当UpdateJson(allprops)
函数在第二个 useEffect 中触发时 - 它被延迟了。 如果我做一个小改动并保存,我会在 console.log 中看到更新 - 但它并没有解决问题。
我也试过添加这个:
const [rerender, setRerender] = useState(false);
并在同一个 useEffect 中添加setRerender(!rerender)
。
我还尝试在父级中创建一个 useEffect:
useEffect(()=>{
console.log(jsonList)
},[publishprops.buysideChoice])
所以...我知道 useEffect 是一个异步函数。 我不明白的是如何调整它。 我读了一些关于你需要如何使用以前的状态。 我以为我已经通过回调解决了这个问题: choosebyprops.setJsonList(jsonList => [...jsonList, UpdateJson(allprops)]);
真的对这整个概念感到困惑。
好的,经过一番尝试后,我决定重新渲染父组件,看看会发生什么……你猜不出来 - 这就是有效的方法。
我将此添加到父级:
useEffect(()=>{
setRerender(!rerender)
},[choiceOrder])
然后我将重新rerender
传递给孩子。 然后,如果父级的重新渲染状态发生任何变化,我将子级的 useEffect 更改为触发。
useEffect(()=>{
const choiceOrder = choosebyprops.choiceOrder;
const setJsonList = choosebyprops.setJsonList
if (choiceOrder.includes(attrChoice) && choiceOrder[choiceOrder.length-1]==attrChoice) {
console.log('this json1',choosebyprops.jsonList)
setJsonList(jsonList => [...jsonList, UpdateJson(allprops)]); //delayed
}
},[choosebyprops.rerender])
现在......对我来说,我似乎多次重新渲染它 - 但嘿它有效。
仍然会喜欢一个解释,因为从我收集到的:
这对我来说听起来真的错了:/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.