【问题标题】:Invalid exhaustive deps in react hooks反应钩子中无效的详尽部门
【发布时间】:2021-03-12 05:52:09
【问题描述】:

我正在使用 react hook 使用 axios 从 covid api 获取数据,但它会引发错误

React Hook useEffect has a missing dependency: 'countries'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

国家是我所在的州

代码:

const [countries,setCountries]=useState([]);

  useEffect(()=>{
    axios.get('https://disease.sh/v3/covid-19/countries').then(response=>{
      //console.log(response.data);
      setCountries(response.data);
      console.log(countries);
    }).catch((error)=>{
      console.log(error);
    })

  },[]);

我已经尝试过其他论坛提供的所有解决方案,但某些解决方案提到了这一点。为什么这段代码不起作用?

【问题讨论】:

  • 在调用setCountries() 后不要登录countries。这就是为什么 useEffect() 需要它作为依赖项。
  • 错误描述了问题所在。您在useEffect 中使用countries(一个状态值)而不将其声明为依赖项(useEffect(()=>{/*...*/}, [countries]);)。因此,正如 PatricRoberts 评论的那样,删除 console.log。无论如何它都会产生陈旧的数据。
  • @Yoshi 您不应该将其声明为依赖项,否则副作用将陷入无限循环。
  • 如果我这样做,日志会出现在无限循环中,但我希望它仅在页面刷新时发生
  • 另外值得注意的是,countries 的值不会在钩子中更新,所以如果你在那里记录它,你会得到countries 的“旧”值。要在那里查看新数据,您需要记录 response.data

标签: javascript reactjs axios react-hooks use-effect


【解决方案1】:

如果您在钩子中使用countries,则应将其添加到您的部门。否则,您将读取一个陈旧的值,因为状态值 countries 尚未更新:

useEffect(()=>{
    axios.get('https://disease.sh/v3/covid-19/countries').then(response=>{
      //console.log(response.data);
      setCountries(response.data);
      console.log(countries);
    }).catch((error)=>{
      console.log(error);
    })
  },[countries]);

但是,在您的情况下 我建议不要将 countries 添加到您的部门,因为您还会在挂钩中调用 setCountries。这样,您的钩子将再次输入,因为 countries 已更改。 如果需要,您应该记录钩子之外的国家/地区的值。

console.log(countries);

useEffect(()=>{
    axios.get('https://disease.sh/v3/covid-19/countries').then(response=>{
      //console.log(response.data);
      setCountries(response.data);
    }).catch((error)=>{
      console.log(error);
    })
  },[]);

【讨论】:

    【解决方案2】:

    如果您添加任何可以在 useEffect 中更改的变量,它将要求您更新依赖数组。您正在记录国家/地区,这就是您看到此警告的原因。

    如果你想深入了解 useEffect,以及关于 Dan Abramov 的关于 A complete Guide To Useeffect 的依赖数组博客将非常有帮助

    【讨论】:

      猜你喜欢
      • 2020-06-15
      • 2020-12-02
      • 2019-08-17
      • 1970-01-01
      • 1970-01-01
      • 2019-09-25
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      相关资源
      最近更新 更多