簡體   English   中英

React Hook useEffect 缺少依賴項

[英]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變為2fetchProduct中的 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掛鈎。 每當該特定值/依賴性發生變化時。

https://reactjs.org/docs/hooks-effect.html#:~:text=React%20to%20skip%20applying%20an%20effect%20if%20certain%20values%20haven%E2%80%99t%20changed%20between %20re%2Drenders

您在效果中使用了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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM