我创建了一个简单的组件,但我在状态更新方面遇到问题。 我知道正确的解决方案,但我的问题是:为什么这段代码不起作用?
import * as React from "react";
import {useEffect, useState} from "react";
type CountdownProps = {
start: number;
}
export const Countdown: React.FunctionComponent<CountdownProps> = ({start}: CountdownProps) => {
const [seconds, setSeconds] = useState<number>(start);
useEffect(() => {
setInterval(() => setSeconds(seconds - 1), 1000);
}, []);
return (<>{seconds}</>);
};
最佳答案
这是 React hooks 的一个已知问题,当涉及到 useInterval 时,Dan 在 Overreacted 的一篇博客文章中谈到了这一问题。
The problem is that
useEffect
captures the the initial value passed to CountDowninitValue
from the first render. We never re-apply the effect so the closure in setInterval always references theinitValue
from the first render, andinitValue - 1
is alwaysinitValue
.
有趣的事实
You can actually check that the interval is actually updating every second by adding a
console.log
to the statement but it's always gettinginitValue
. Try it out here https://repl.it/repls/MedicalMealyPentagon
有关解决方案,请阅读上面的文章。
关于javascript - 为什么功能组件中没有声明更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59613617/