【发布时间】:2021-07-01 02:42:11
【问题描述】:
我遇到了一个奇怪的问题,在 setState() 钩子函数中更改克隆的顺序会改变预期的行为。
我试图每秒增加一秒的值。但是这样做会直接导致秒数增加 2 而不是 1。
这行得通
const [value, setValue] = useState(new Date());
useEffect(() => {
const interval = setInterval(
() =>
setValue((value) => {
const clonedDate = new Date(value.getTime());
clonedDate.setSeconds(clonedDate.getSeconds() + 1); // Add one second to the time
return clonedDate;
}),
1000
);
return () => {
clearInterval(interval);
};
}, []);
这增加了两秒而不是一秒
const [value, setValue] = useState(new Date());
useEffect(() => {
const interval = setInterval(
() =>
setValue((value) => {
value.setSeconds(value.getSeconds() + 1);
const clonedDate = new Date(value.getTime());
return clonedDate;
}),
1000
);
return () => {
clearInterval(interval);
};
}, []);
【问题讨论】:
-
不确定,但在第一个中,您每次都在创建新对象,然后增加秒数,但在第二个中,您在现有对象中增加,然后创建新对象..可能就像它持有引用第二个中的前一个值对象
标签: reactjs date settimeout