![](/img/trans.png)
[英]UseEffect - React Hook useEffect has a missing dependency:
[英]missing dependency for React Hook useEffect
嗨,这是我的代码: https://codesandbox.io/s/busy-tdd-e8s1ej?file=/src/App.js
对于 react-router-dom,我使用的是 ver5.2+。
我终生无法找出缺失的依赖项,我尝试在此处搜索答案,但它告诉我将我添加到依赖项中无济于事。
感谢您对这个问题的任何启发,谢谢
因为您使用的是在useEffect
之外定义的东西(在本例中fetchProduct
函数),react 将发出警告,说明如果fetchProduct
function 内部发生变化, useEffect
将不会捕获该变化。 例如:假设match.params.id
中的fetchProduct
在页面首次加载时等于1
,但稍后match.params.id
变为2
, fetchProduct
中的 fetchProduct useEffect
仍将使用1
作为match.params.id
因为useEffect
没有捕捉到变化。
所以要解决警告,有 2 个选项。 首先是在 useEffect 中编写fetchProduct
useEffect
逻辑:
useEffect(() => {
axios
.get(`https://fakestoreapi.com/products/?id=${match.params.id}`)
.then((res) => {
setData(res.data);
console.log(res.data);
})
.catch((err) => console.log(err));
}, [match.params.id]);
在依赖数组中match.params.id
以确保useEffect
是最新的。
但是如果你需要重用fetchProduct
function,那么你应该这样做:
const fetchProduct = useCallback(() => {
axios
.get(`https://fakestoreapi.com/products/?id=${match.params.id}`) // use match to get product id
.then((res) => {
setData(res.data);
console.log(res.data);
})
.catch((err) => console.log(err));
}, [match.params.id]);
useEffect(() => {
fetchProduct();
}, [fetchProduct]);
这是一个警告,请仔细阅读useEffect()
的文档
https://reactjs.org/docs/hooks-effect.html 。
每当您在数组中添加依赖项时,它都会监视所有这些值并重新运行useEffect
挂钩。 每当该特定值/依赖性发生变化时。
您在效果中使用了fetchProduct
function,因此它是一个依赖项。 错误消息应该告诉你。
修复它的一种方法是将fetchProduct
function 移到效果中。 然后match
将成为效果的依赖项,但您可能希望match
发生变化,您最有可能希望获取新产品。
useEffect(() => {
// function fetchProducts
const fetchProduct = () => {
axios
.get(`https://fakestoreapi.com/products/?id=${match.params.id}`) // use match to get product id
.then((res) => {
setData(res.data);
console.log(res.data);
})
.catch((err) => console.log(err));
};
fetchProduct();
}, [match]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.