繁体   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