[英]Executing a function only after setState is done
I'm using openAi API to talk to ChatGPT in my React App, I want to send the request to ChatGPT after my message is asynchronously added to messages
array, Is there a way to do it?我在我的 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 },
]);
});
}
If you're just wanting the messages to appear in order, you don't need to wait for the re-render.如果您只是希望消息按顺序显示,则无需等待重新呈现。 Even if the response comes through instantly (which is very unlikely), the user's messages will still show before the response messages get appended to the array.即使响应立即通过(这不太可能),用户的消息仍会在响应消息附加到数组之前显示。
Here's a code sandbox that shows this in action. 这是一个代码沙箱,展示了这一点。
Note that you should also be using the callback version of setMessages
since you're relying on the previous state -请注意,您还应该使用setMessages
的回调版本,因为您依赖于之前的 state -
const addMessage = (msg: string) => setMessages((prev) => [...prev, msg]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.