简体   繁体   English

useEffect 中的无限循环,useEffect 中的 async/await

[英]Infinite loop in useEffect, async/await in useEffect

I know this question has been asked a lot - but I need some help!我知道这个问题已经被问了很多 - 但我需要一些帮助!

I would like getExistingCards() to execute and setCards before updateActivity() .我希望getExistingCards()updateActivity()之前执行和setCards

getExistingCards() should setCards if 1) cards exist, and 2) cards is an empty array (I don't want to setCards to existingCards if cards is already set to existingCards !) getExistingCards()应该setCards如果1) 卡片存在,并且 2) cards一个空数组(如果cards已经设置为existingCards ,我不想将 setCards 设置为existingCards !)

The below works perfectly, so this shouldn't have to change.下面的工作完美,所以这不应该改变。

  const [cards, setCards] = useState([]);

  useEffect(() => {
    updateActivity(path, cards);
  }, [cards]);

Adding getExistingCards() below causes an infinite loop (which makes sense because I know I'm setting state within the effect, and cards is also in the dependency array):在下面添加getExistingCards()会导致无限循环(这是有道理的,因为我知道我在效果中设置状态,并且卡片也在依赖项数组中):

  // useLayoutEffect executes before useEffect
  useLayoutEffect(() => {
    const getExistingCards = () => {
      if (activity) {
        if (path.field === "activity_milestones" || path.field === "activity_indicators") {
          let existingItems = activity[path.field]
          if (existingItems) {
            setCards(existingItems);
          }
        }
      }
    };
    getExistingCards();
  }, []);

  useEffect(() => {
    updateActivity(path, cards);
  }, [cards]);

I also tried to add both updateActivity() and getExistingCards() to the useEffect implementing async/await, but realize getExistingCards() is not actually a promise.我还尝试将updateActivity()getExistingCards()添加到实现异步/等待的useEffect中,但意识到getExistingCards()实际上并不是一个承诺。

Any insight would be really appreciated - thank you任何见解将不胜感激 - 谢谢

Just check the length of cards before your execute your embedded function在执行嵌入式功能之前只需检查卡片的长度

  useEffect(() => {
   if (cards.length === 0) updateActivity(path, cards);
  }, [cards]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM