簡體   English   中英

僅在 setState 完成后執行 function

[英]Executing a function only after setState is done

我在我的 React 應用程序中使用 openAi API 與 ChatGPT 對話,我想在我的消息異步添加到messages數組后將請求發送到 ChatGPT,有沒有辦法做到這一點?

function addMessage() {
  setMessages([...messages, { writer: "Me", text: "Hi ChatGPT, how are you ?" }]);

  // execute this after the asynchronous setState above is over
  getResponse();
}

function getResponse() {
  getOpenAiCompletions(text, temp).then((response) => {
      setMessages([
        ...messages,
        { writer: "ChatGPT", text: response.data.choices[0].text },
      ]);
    });
}

如果您只是希望消息按順序顯示,則無需等待重新呈現。 即使響應立即通過(這不太可能),用戶的消息仍會在響應消息附加到數組之前顯示。

這是一個代碼沙箱,展示了這一點。

請注意,您還應該使用setMessages的回調版本,因為您依賴於之前的 state -

const addMessage = (msg: string) => setMessages((prev) => [...prev, msg]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM