Typescript setInterval error: XYZ is already declared in the upper scope
Typescript setInterval error: XYZ is already declared in the upper scope
我在创建处理程序函数并尝试将当前引用设置为状态值加 1 时遇到奇怪的错误:
const useTimer = () => {
const [seconds, setSeconds] = useState(0);
const counterRef = useRef(null);
const handleStart = () => {
counterRef.current = setInterval(() => {
setSeconds((**seconds**) => seconds + 1);
}, 1000);
};
return (
<button type="button" onClick={handleStart}>Start</button>
)
}
eslint 现在正在启动那个 'seconds' is already declared in the upper scope on line 8 column 10.
,它是由 setSeconds
的 seconds
参数引起的(在上面的代码片段中用 ** 突出显示)。
问题 1:我是否以编程方式遗漏了某些内容,或者这真的只是一个错误的 eslint 错误?
问题 2:当我从 useRef
中删除 null
时,counterRef.current
带有下划线并带有错误 Type 'Timeout' is not assignable to type 'undefined'.
如何正确初始化 useRef
setInterval
将成为未来的价值?
编辑: 在反应文档中找到 this answer:
If the new state is computed using the previous state, you can pass a function to setState. The function will receive the previous value, and return an updated value.
no-shadow
开始的原因更有意义。感谢所有评论者。
回复。问题 1:此警告有效。您在两个不同的地方声明了两个 不同的 变量,名为 seconds
,这在某些范围内产生了歧义。
const [seconds, setSeconds] = useState(0);
// ^^^^^^^
setSeconds((seconds) => seconds + 1);
// ^^^^^^^
我会通过重命名来解决这个问题:
setSeconds((prevSeconds) => prevSeconds + 1);
回复。问题 2:按如下方式输入您的参考:
// If using NodeJS setInterval:
const counterRef = useRef<NodeJS.Timeout|null>(null);
// If using window.setInterval (ie. in a browser):
const counterRef = useRef<number|null>(null);
编辑:支持在网络浏览器中回复评论 - setInterval
和 setTimeout
return number
。
我在创建处理程序函数并尝试将当前引用设置为状态值加 1 时遇到奇怪的错误:
const useTimer = () => {
const [seconds, setSeconds] = useState(0);
const counterRef = useRef(null);
const handleStart = () => {
counterRef.current = setInterval(() => {
setSeconds((**seconds**) => seconds + 1);
}, 1000);
};
return (
<button type="button" onClick={handleStart}>Start</button>
)
}
eslint 现在正在启动那个 'seconds' is already declared in the upper scope on line 8 column 10.
,它是由 setSeconds
的 seconds
参数引起的(在上面的代码片段中用 ** 突出显示)。
问题 1:我是否以编程方式遗漏了某些内容,或者这真的只是一个错误的 eslint 错误?
问题 2:当我从 useRef
中删除 null
时,counterRef.current
带有下划线并带有错误 Type 'Timeout' is not assignable to type 'undefined'.
如何正确初始化 useRef
setInterval
将成为未来的价值?
编辑: 在反应文档中找到 this answer:
If the new state is computed using the previous state, you can pass a function to setState. The function will receive the previous value, and return an updated value.
no-shadow
开始的原因更有意义。感谢所有评论者。
回复。问题 1:此警告有效。您在两个不同的地方声明了两个 不同的 变量,名为 seconds
,这在某些范围内产生了歧义。
const [seconds, setSeconds] = useState(0);
// ^^^^^^^
setSeconds((seconds) => seconds + 1);
// ^^^^^^^
我会通过重命名来解决这个问题:
setSeconds((prevSeconds) => prevSeconds + 1);
回复。问题 2:按如下方式输入您的参考:
// If using NodeJS setInterval:
const counterRef = useRef<NodeJS.Timeout|null>(null);
// If using window.setInterval (ie. in a browser):
const counterRef = useRef<number|null>(null);
编辑:支持在网络浏览器中回复评论 - setInterval
和 setTimeout
return number
。