useEffect中的无限循环,useEffect中的异步/等待

时间:2019-12-13 18:48:58

标签: reactjs react-hooks setstate use-effect react-state-management

我知道这个问题已经问了很多-但我需要一些帮助!

我希望import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.ScrollPaneConstants; import javax.swing.WindowConstants; public class TxtArTst implements Runnable { @Override // java.lang.Runnable public void run() { createAndShowGui(); } private void createAndShowGui() { JFrame frame = new JFrame("JSP"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); JTextArea textArea = new JTextArea(20, 10); JScrollPane scroll = new JScrollPane(textArea); scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); scroll.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 0)); frame.add(scroll, BorderLayout.LINE_START); frame.setSize(450, 300); frame.setLocationRelativeTo(null); frame.setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new TxtArTst()); } } 执行,getExistingCards()之前 setCards

updateActivity()应该getExistingCards() 如果 1)个卡存在,并且2)setCards 一个空数组 (如果cards已设置为existingCards,我不想将Cards设置为cards!)

以下内容可完美运行,因此不必更改。

existingCards

在下面添加 const [cards, setCards] = useState([]); useEffect(() => { updateActivity(path, cards); }, [cards]); 会导致无限循环(这是有道理的,因为我知道我正在效果中设置状态,并且卡也位于依赖项数组中):

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]); updateActivity()都添加到实现异步/等待的getExistingCards()中,但意识到useEffect实际上不是一个承诺。

任何见解都会受到感激-谢谢

1 个答案:

答案 0 :(得分:0)

在执行嵌入式功能之前只需检查卡的长度

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