[英]Invalid exhaustive deps in react hooks
I am using a react hook to fetch the data from covid api using axios but it throws an error of我正在使用反应挂钩使用 axios 从 covid api 获取数据,但它会引发错误
React Hook useEffect has a missing dependency: 'countries'. Either include it or remove the dependency array react-hooks/exhaustive-deps
where countries is my state我的 state 在哪里
Code:代码:
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);
})
},[]);
I have tried doing every solutions provided by other forums but this is prefectly fine mentioned by some solutions.我已经尝试过其他论坛提供的所有解决方案,但是某些解决方案提到了这一点。 Why isnt this code working?
为什么这段代码不起作用?
If you use countries
in your hook, you should add it to your deps.如果您在挂钩中使用
countries
地区,则应将其添加到您的部门。 Otherwise you will read a stale value because the state value countries
was not yet updated:否则,您将读取过时的值,因为 state 值
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]);
However in your case I would advice against adding countries
to your deps , because you also call setCountries
in your hook.但是,在您的情况下,我建议您不要将
countries
地区添加到您的 deps中,因为您还会在钩子中调用setCountries
。 This way your hook would be entered again because countries
has changed.这样你的钩子就会再次进入,因为
countries
已经改变了。 You should rather log the value of countries outside of your hook if you need it.如果需要,您应该记录钩子之外的国家/地区的价值。
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);
})
},[]);
If you are adding any variables which can be changed in useEffect it will ask you to update the dependency array.You are logging countries that's why you are seeing this warning.如果您要添加任何可以在 useEffect 中更改的变量,它会要求您更新依赖数组。您正在记录国家,这就是您看到此警告的原因。
If you want to understand useEffect in depth, and about the dependency array blog by Dan Abramov about A complete Guide To Useeffect will be very helpful如果您想深入了解 useEffect 以及 Dan Abramov 的依赖数组博客,关于A complete Guide To Useeffect将非常有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.