在启用exhaustive-deps规则的React Typescript中,当我定义一个ref并在effect内部使用它时,语法检查器会认为这是正确的:
const stringRef: RefObject<string> = useRef("Hello World!");
useEffect(() => {
console.log(stringRef.current);
}, []) // no warning, the linter detects that I'm using a ref
不过,当我把这个效果放在一个自定义钩子里时,linter会抱怨我应该将ref包含在依赖项数组中:
const stringRef: RefObject<string> = useRef("Hello World!");
useCustomHook(stringRef);
// in another-file.ts
const useCustomHook = (ref: RefObject<string>) => {
useEffect(() => {
console.log(ref.current);
}, []) // ESLint: React Hook useEffect has a missing dependency: 'ref'. Either include it or remove the dependency array.(react-hooks/exhaustive-deps)
}
从语义上讲,没有什么改变,然而linter没有识别出ref是一个RefObject(即使我已经这样输入了)。
现在的重要问题是:如何让linter知道给定的依赖项不需要包含在依赖项数组中,而不会抑制警告?
对我来说,这是一个主要的缺点,因为我无法将我的effects转换为自定义hooks,而不被linter抱怨。
感谢您的帮助。
useRef
返回的ref
对象不稳定吗?你可以将其安全地用作自定义 effect 中的依赖项。 - thedude