我正在使用 typescript、react 和 framer-motion。
我创建了一个计数器组件,其数量动态增加。
但是,我遇到了一些 ts 错误。
类型 '() => void' 不可分配给类型 'undefined'.ts(2322) 错误发生在①处。
错误无法调用可能为“未定义”的对象。ts(2722) 发生在②处。
export const Index: React.FunctionComponent = () => {
return (
<Counter valueTo={30} totalDuration={2 + 0.5} />%
);
};
import { useEffect, useRef, useState } from 'react';
interface Props {
valueFrom: number;
valueTo: number;
totalDuration: number;
}
export const Counter: React.FunctionComponent<Props> = ({ valueFrom = 0, valueTo = 100, totalDuration = 1 }) => {
const [count, setCount] = useState(valueFrom);
useInterval(() => {
if (count < valueTo) {
setCount(count + 1);
}
}, (totalDuration / valueTo) * 1000);
return count;
};
const useInterval = (callback: () => void, delay: number) => {
const savedCallback = useRef();
// Remember the latest callback.
useEffect(() => {
// ①
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
// ②
savedCallback.current();
}
if (delay !== null) {
const id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
};
答案 0 :(得分:1)
您需要声明 ref 具有该类型(useRef 使用泛型)并确保该函数不是未定义的(默认情况下,useRef 的“当前”为未定义)。您可以通过以下方式执行此操作:(查看您标记的位置)
x