【问题标题】:returning promise from useEffect从 useEffect 返回承诺
【发布时间】:2021-01-14 01:22:19
【问题描述】:

我正在浏览文章https://www.robinwieruch.de/react-hooks-fetch-data

它给出了下面2个sn-ps来演示如何处理useEffect中的promise。第一个会抛出错误,而第二个不会。

第一个 sn-p -

  useEffect(async () => {
    const result = await axios(
      'https://hn.algolia.com/api/v1/search?query=redux',
    );
 
    setData(result.data);
  }, []);

第二个sn-p-

useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        'https://hn.algolia.com/api/v1/search?query=redux',
      );
 
      setData(result.data);
    };
 
    fetchData();
  }, []);

为什么第二个不抛出错误,当fetchdata()被调用时它会返回一个promise,因此useEffect也会返回一个promise。第二个 sn-p 和第一个有什么不同?

【问题讨论】:

  • when fetchdata() is called it will return a promise, and thus a promise will be returned from useEffect too.
  • 第一条语句抛出什么错误?
  • 两者都返回undefined。一个 useEffect 函数根本不能是async

标签: reactjs react-hooks


【解决方案1】:

对于 useEffect 挂钩,您只能返回 nothingcleanup 函数。 第一个 sn-p 抛出错误的原因是因为您将函数标记为 async 并且标记为 async 的函数将始终返回一个 Promise。

//The function is marked async
 useEffect(async () => {
    const result = await axios(
      'https://hn.algolia.com/api/v1/search?query=redux',
    );
 
    setData(result.data);
  }, []);

它违反了不返回任何内容或返回清理函数的规则。

然而在第二个 sn-p 中,你使用 useEffect 函数来调用异步函数,但是由于 useEffect 函数本身不是异步的,这意味着它没有返回一个 Promise

//this is not marked async
  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        'https://hn.algolia.com/api/v1/search?query=redux',
      );
 
      setData(result.data);
    };
 
    fetchData();
  }, []);

【讨论】:

    【解决方案2】:

    据我所知,你不能直接在 React Hook 上使用 Promise。您可以在函数内部使用它,它会起作用。钩子在那里,所以你不需要在 React 中使用类。

    更多关于 Hooks => https://reactjs.org/docs/hooks-overview.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-15
      • 1970-01-01
      • 2021-01-29
      • 2019-08-14
      • 2016-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多