【问题标题】:React Hook useEffect has a missing dependency (function defined in context)React Hook useEffect 缺少依赖项(在上下文中定义的函数)
【发布时间】:2020-05-28 06:51:02
【问题描述】:

我收到错误: 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 函数放在返回函数中。我想我要问的是最好的方法是什么?

【问题讨论】:

  • 您不想将setPage 依赖项放入依赖项数组的原因是什么

标签: react-hooks react-context use-effect


【解决方案1】:

如果您确定它不会对您的应用程序产生不良影响,那么您可以使用 // eslint-disable-next-line react-hooks/exhaustive-deps 忽略 linter

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;

【讨论】:

    猜你喜欢
    • 2021-02-23
    • 2019-10-24
    • 2020-10-26
    • 2020-07-24
    • 2020-03-07
    • 2020-02-25
    • 2020-06-11
    • 2020-03-30
    • 2020-12-29
    相关资源
    最近更新 更多