![](/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.