我在react admin中有两个组件,子组件设置父组件的状态。
子组件具有useEffect来触发父组件中的以下方法
const [approved, setAproved] = useState([]);
useEffect(() => {
console.log(JSON.stringify(approved))
}, [approved])
const setapprovedamount = (id, approvedAmount) => {
if(approved.length!==0)
{
// if the child run 3 times
// this line runs 3 times
console.log("set Aproved with" +id+ " and amount : "+approvedAmount)
// but this line update only the last object
setAproved(
approved.map(item =>
(item.id == id)
? {...item, totalApproved : approvedAmount}
: item
)
)
}
else
{
setAproved(approved =>[...approved, {
id: id,
totalApproved: approvedAmount
}] )
}
}
useEffect(() => {
console.log(JSON.stringify(approved))
}, [approved])
So **for example** if I have 3 times load, the Console is:
file.js:168 set Aproved with44 and amount : 799.71
file.js:168 set Aproved with45 and amount : 845.98
file.js:168 set Aproved with46 and amount : 890.83
file.js:96
[{"id":44,"totalApproved":null},{"id":45,"totalApproved":null},{"id":46,"totalApproved":890.83}]
因此,该方法在触发时运行3次,但它只设置父组件中状态数组中呈现的最后一个值
因为状态和生命周期是如何工作的。
如果您想通过setState
触发多个连锁的状态更新,您需要让组件在每次状态更新时完成其循环——首先要做的事情。
因此,基本的解决方案是暗示使用链式setTimeout
调用来委托每个状态更新,让每个函数调用完成一个组件,整个生命周期。
setTimeout(function() {
setState(firstState)
setTimeout(function() {
setState(secondState)
});
});