React Hook useEffect 缺少依賴項(在上下文中定義的函數) (React Hook useEffect has a missing dependency (function defined in context))


問題描述

React Hook useEffect 缺少依賴項(在上下文中定義的函數) (React Hook useEffect has a missing dependency (function defined in context))

我收到錯誤消息:React Hook useEffect 缺少依賴項:'setSelectedPage'。要么包含它,要么移除依賴數組 react‑hooks/exhaustive‑deps

const Blah = props => {
    const { setPage } = useContext(GlobalContext);

    useEffect(() => {
        setPage("new project");
    }, []);

    return (
        <NewProjectState>
            <Index props={props} />
        </NewProjectState>
    );
};

export default Blah;

我知道 react 希望我在 useEffectsetPage 函數> 但是它顯然在其他地方使用。我確實想知道為什麼不簡單地將 setPage 函數放在返回函數中。我想我要問的是最好的方法是什麼?


參考解法

方法 1:

If you are sure it won't affect your application in bad ways, then you can ignore the linter with // eslint‑disable‑next‑line react‑hooks/exhaustive‑deps

const Blah = props => { 
  const { setPage } = useContext(GlobalContext);

  useEffect(() => {
    setPage("new project");
    // eslint‑disable‑next‑line react‑hooks/exhaustive‑deps
  }, []);

  return (
    <NewProjectState>
        <Index props={props} />
    </NewProjectState>
  );
};

export default Blah;

(by mdc29JCQuintas)

參考文件

  1. React Hook useEffect has a missing dependency (function defined in context) (CC BY‑SA 2.5/3.0/4.0)

#react-context #react-hooks #use-effect






相關問題

在項目中使用 Context API 我以前會在異步操作創建者中使用 Redux? (Using Context API in a project I would have previously used Redux in - async action creators?)

Nextjs 和上下文 API (Nextjs and Context API)

從 redux-saga 函數訪問 React 上下文值 (Access React context value from redux-saga function)

如何在 Django 應用程序中用 react ContextAPI 替換 Redux (How can you replace Redux by the react ContextAPI in a Django App)

從深度嵌套的組件更新狀態而不重新渲染父組件 (Update state from deeply nested component without re-rendering parents)

更新 useContext 中的值時,組件不會重新呈現 (Component not re rendering when value from useContext is updated)

為什麼我無法從反應上下文訪問變量?你能找出錯誤嗎? (Why am I not able to access variable from react context? Can you identify the mistake?)

React Hook useEffect 缺少依賴項(在上下文中定義的函數) (React Hook useEffect has a missing dependency (function defined in context))

React Context 是道具鑽探的解毒劑嗎? (Is React Context an antidote for prop drilling?)

主題提供者問題 (Theme Provider issue)

打字稿反應上下文+類型'{}'沒有調用簽名 (Typescript react context + Type '{}' has no call signatures)

next.js socket.io 使用效果不更新套接字消息 (next.js socket.io useeffect not updating on socket message)







留言討論