問題描述
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 希望我在 useEffect
setPage 函數> 但是它顯然在其他地方使用。我確實想知道為什麼不簡單地將 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;