如何解决"u​​seEffect缺少依赖项"在自定义钩子中 [英] How do I fix "useEffect has a missing dependency" in custom hook

查看:47
本文介绍了如何解决"u​​seEffect缺少依赖项"在自定义钩子中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用自定义钩子来从API中提取一些数据,以供一组React函数组件使用.但是,esLint会发出一个可爱的警告:

I'm using a custom hook to get pull some data in from an API for use across a set of React function components. However, esLint throws up a lovely warning:

反应挂钩useEffect缺少依赖项:'fetchFromAPI'.任何一个包括它或删除依赖项数组.

React Hook useEffect has a missing dependency: 'fetchFromAPI'. Either include it or remove the dependency array.

我不认为这是依赖项,因为它位于 useFetch()本身内.我在使用 await 时需要这样做.我究竟做错了什么?可以仅关闭此行的警告吗?还是我应该使用更规范的语法?

I didn't think it's a dependency, as it's inside useFetch() itself. I need to do it as I'm using await. What am I doing wrong? Is it ok to just turn off the warning for this line? Or is there a more canonical syntax I should be using?

function useFetch (url) {
  const [data, setData] = useState(null);

  async function fetchFromAPI() {
    const json = await( await fetch(url) ).json();
    setData(json);
  }

  useEffect(() => {fetchFromAPI()},[url]);

  return data;
};

export {
  useFetch
};

推荐答案

我建议您在useEffect自身内部定义异步函数:

I suggest you to define async function inside useEffect itself:

function useFetch (url) {
  const [data, setData] = useState(null);
  useEffect(() => {
    async function fetchFromAPI() {
      const json = await( await fetch(url) ).json();
      setData(json);
    }
    fetchFromAPI()
  },[url]);

  return data;
};

您可以从

You can take a look at valid example from doc faqs which uses async function inside useEffect itself:

function ProductPage({ productId }) {
  const [product, setProduct] = useState(null);

  useEffect(() => {
    // By moving this function inside the effect, 
    // we can clearly see the values it uses.
    async function fetchProduct() {
      const response = await fetch('http://myapi/product' + productId);
      const json = await response.json();
      setProduct(json);
    }

    fetchProduct();
  }, [productId]); // ✅ Valid because our effect only uses productId
  // ...
}

这篇关于如何解决"u​​seEffect缺少依赖项"在自定义钩子中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆