为什么我尝试获取区块链数据的 useEffect 会无限循环,而我的异步函数仍然 returns Promise pending

Why my useEffect that tries to get blockchain data is looping infinitely and my async func still returns Promise pending

我正在尝试在 useEffect 挂钩中使用异步等待从测试网区块链获取一些数据,但我遇到了 2 个问题:

  1. 异步函数returns一个Promise,为什么会这样?异步等待不应该自动解决承诺并给我数据吗?我尝试用 Promise.resolve 解决它但没有用,它仍然告诉我活动是一个处于挂起状态的 Promise。
  2. 它进入了一个无限循环,我仍然不明白为什么。

代码如下:

  useEffect(() => {
    const getCampaigns = async() => {
      const campaigns = await factory.methods.getDeployedCampaigns().call()
      return campaigns
    }
    const campaigns = getCampaigns();
    setCampaigns(Promise.resolve(campaigns));

    console.log('campaigns: ', campaigns);
  })

您没有依赖项数组。

useEffect(() => {
   const getCampaigns = async() => {
      const campaigns = await factory.methods.getDeployedCampaigns().call()
      return campaigns
   }
   
   const campaigns = getCampaigns();
   setCampaigns(Promise.resolve(campaigns));
   console.log('campaigns: ', campaigns);
}, [])

试试这个

useEffect(() => {
  const getCampaigns = async() => {
    const campaigns = await factory.methods.getDeployedCampaigns().call()
    setCampaigns(campaigns);
  }

  getCampaigns();
}, []);

useEffect 调用中的空数组使其表现得像组件挂载并且只执行一次(假设工厂方法在挂载时初始化)并且由于 getDeployedCompanigns Promise 已经解决我只是在 getCampaigns 函数中设置状态.

阅读这篇文章了解详情:https://devtrium.com/posts/async-functions-useeffect