【发布时间】: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