【发布时间】:2022-01-06 05:42:07
【问题描述】:
我使用useEffect() 获取Firestore 快照并并行我想计算一个值:
const [counter, setCounter] = useState({ mona: 0, phil: 0 });
useEffect(() => {
onSnapshot(q, (snapshop) => {
setTasks(
snapshop.docs.map((doc) => {
if (doc.data().wer === "Mona") {
console.log("Mona + 1"); // This get's executed as expected (e.g. 3 times)
setCounter({ ...counter, mona: counter.mona + 1 });
}
if (doc.data().wer === "Phil") {
console.log("Phil + 1"); // This get's executed as expected (e.g. 6 times)
setCounter({ ...counter, phil: counter.phil + 1 });
}
return {
...doc.data(),
id: doc.id,
timestamp: doc.data().timestamp?.toDate().getTime(),
};
})
);
setLoading(false);
});
}, []);
useEffect(() => {
console.log({ counter }); //this get's executed only 2 times.
}, [counter]);
当map()中的console.log()正确执行时,为什么setCounter没有正确执行或更新计数器?
console.log({ counter }); 顺便说一句:
{counter: {mona: 0, phil: 0}}
{counter: {mona: 0, phil: 1}}
【问题讨论】:
标签: javascript reactjs use-effect use-state