繁体   English   中英

React Hook useEffect 缺少依赖项:“url”。 包括它或删除依赖数组 react-hooks/exhaustive-deps

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

useEffect(() => {
  fetch(url)
    .then(response => response.json())
    .then(data => setData(data[0]))
    .catch(err => console.warn(err))
}, [cityKey])

我该如何解决这个警告?

useEffect(() => {
  fetch(url)
    .then(response => response.json())
    .then(data => setData(data[0]))
    .catch(err => console.warn(err))
}, [cityKey,url])

根据警告建议的解决方案,在依赖项数组中包含url

useEffect(() => {
  fetch(url)
    .then(response => response.json())
    .then(data => setData(data[0]))
    .catch(err => console.warn(err))
}, [cityKey, url])

或者,您可以禁用警告(但不推荐):

useEffect(() => {
  fetch(url)
    .then(response => response.json())
    .then(data => setData(data[0]))
    .catch(err => console.warn(err))
  // eslint-disable-next-line react-hooks/exhaustive-deps
}, [cityKey])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM