【问题标题】:Getting react-hooks/exhaustive-deps error while trying to deploy a react app尝试部署 React 应用程序时出现 react-hooks/exhaustive-deps 错误
【发布时间】:2021-03-23 22:45:06
【问题描述】:

我正在尝试部署一个反应应用程序。该代码/应用程序在我的本地端运行良好。但是,当我尝试部署它时,我收到此错误:
React Hook useEffect has a missing dependency: 'endGame'. Either include it or remove the dependency array react-hooks/exhaustive-deps
这是与错误相关的代码:

useEffect(() => {
    if (isTimeRunning && timeRemaining > 0) {
      setTimeout(() => {
        setTimeRemaining((time) => time - 1);
      }, 1000);
    } else if (timeRemaining === 0) {

      // eslint-disable-next-line react-hooks/exhaustive-deps
      return endGame();
    }
  }, [timeRemaining, isTimeRunning]);

我尝试了几件事,包括将 endGame() 函数添加到数组(作为 useEffect 的第二个参数),但这样做会破坏我的应用程序。
要查看整个代码/项目,请转到 repo,这里:https://github.com/umbur/SpeedTypingGame
附言在将此问题标记为不相关或类似之前,请询问我更多详细信息,谢谢!

【问题讨论】:

    标签: reactjs deployment react-hooks use-effect react-functional-component


    【解决方案1】:

    将函数添加到依赖项时不应调用该函数,而应传递函数引用。

    试试这个:[timeRemaining, isTimeRunning, endGame]

    【讨论】:

    • 感谢您的回答,但这样做会破坏应用程序计时器的功能。 endGame() 函数应该在timeRemaining === 0 时调用,这就是为什么它需要在else if 条件下
    • endGame 添加到useEffect 依赖数组会破坏您的应用程序?
    • 是的。但是,我找到了解决方案。请参阅我的回答,提供。
    【解决方案2】:

    所以基本上问题是我没有正确应用(或忽略lint error)这个://eslint-disable-next-line react-hooks/exhaustive-deps 我应该在那个 useEffect 钩子的最后一行应用它。 解决此类问题的正确方法是:

      useEffect(() => {
        if (isTimeRunning && timeRemaining > 0) {
          setTimeout(() => {
            setTimeRemaining((time) => time - 1);
          }, 1000);
        } else if (timeRemaining === 0) {
          return endGame();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [timeRemaining, isTimeRunning]);
    

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 2020-05-01
      • 2021-04-15
      • 2020-06-08
      • 2022-08-18
      • 2020-03-11
      • 2020-01-18
      相关资源
      最近更新 更多