簡體   English   中英

useEffect 在自定義鈎子中使用 ref 缺少依賴項警告

[英]useEffect missing dependency warning with ref in custom hook

在 React Typescript 啟用了窮舉-deps 規則時,當我定義一個 ref 並在效果內部使用它時,linter 就可以了:

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 知道給定的依賴項不需要包含在依賴項數組中而不抑制警告?

對我來說,這是不可能的一個主要缺點,因為我無法在沒有 linter 抱怨的情況下將我的效果轉換為自定義鈎子。

謝謝你的幫助。

您不能開箱即用地對其進行配置。

linter ( eslint ) 是一個 static 代碼分析器。 它只分析文本模式而不編譯代碼,即它不知道所寫內容的“含義”。

例如,它看到“ use***() ”模式並認為它是一個自定義鈎子,然后它使用鈎子規則模式驗證它,就像在if語句中沒有這樣的文本一樣。

你自己看:

提醒:自定義鈎子是帶有“use”前綴的 function使用鈎子的 function。

// NOT A CUSTOM HOOK, just a function with 'use' prefix
const useConsole = () => console.log("hello");

// Normal function
const logHello = () => console.log("hello2");

const Component = () => {
  if (true) {
    // Warning - React hook is called conditionally
    useConsole();

    // OK
    logHello();
  }
  return <>Example</>;
};

編輯 Eslint 示例

但是,您始終可以 提出自定義規則來識別同一 scope 中的RefObject<string>useEffect

從 Typescript 編譯器方面來看,它沒有違反任何內容,因為用例與useEffect類型匹配。

useEffect1useEffect2之間的區別在於stringRef是一個常量,因此根據定義const不會更改,但在示例 2 中ref是一個可以更改的變量,因此您必須將參數添加為依賴項。

您可以使用 // eslint-disable-next-line react-hooks/exhaustive-deps 禁用該規則,否則您可以將 ref 移動到 useEffect

useEffect(() => {
   // other code
   ...

   // eslint-disable-next-line react-hooks/exhaustive-deps
}, []) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM