我正在制作的游戏的一部分需要查询 gpt-4o 询问两个人是否见过面。提供了初始人,用户必须输入他们认为见过初始人的人的姓名。通过输入字段提交猜测后,将返回包含文本“true”或“false”的承诺。
根据响应,我需要更新“gameState”中包含的一些值并将它们传递到 gpt-4o 的另一个查询中。
但是,由于响应是一个承诺,因此我无法使用响应来更新全局变量。截至目前,“gameState”已在异步函数内初始化。当函数运行时,“gameState”会发生变化,但是当我输入不同的名称时,它会重置并且“count”不会增加。
如何使用 Promise 中的信息来更新变量,等到提交另一个输入,然后将这些更新的变量与新输入一起传递到另一个查询中?
import './App.css';
import React, { useState, useRef } from 'react';
const { OpenAI } = require('openai');
const openai = new OpenAI({ apiKey: '[myKey}');
function App() {
const inputRef = useRef();
let people = ["Donald Trump", "Taylor Swift"];
const handleSubmit = (event) => {
play(inputRef.current.value, people[0], people[1]);
event.preventDefault();
}
async function play(guess, p1, p2) {
let gameState = {
currentPerson: p1,
count: 0
}
const completion = await openai.chat.completions.create({
messages: [
{
role: "system",
content: "respond with true or false in lower case depening on if these people have met"
},
{
role: "user",
content: `${gameState.currentPerson}, ${guess}`
},
],
model: "gpt-4o",
});
if(completion.choices[0].message.content === "true" && guess === p2) {
console.log("You Win!");
gameState.count++;
console.log(gameState);
} else if(completion.choices[0].message.content === "true") {
console.log("Correct");
gameState.count++;
gameState.currentPerson = guess;
console.log(gameState);
} else {
console.log("Wrong");
}
}
return (
<form onSubmit={handleSubmit} >
<label >
Name:
<input name="guessInput" type="text" ref={inputRef} />
</label>
<button type="submit">
Submit
</button>
</form>
);
}
export default App;
我尝试将输入事件处理程序更改为异步函数并在那里进行 API 调用,但导致了错误。
添加常规变量是不够的,如官方 React 文档
所示局部变量在渲染之间不会持续存在。当 React 第二次渲染这个组件时,它会从头开始渲染它——它不会考虑对局部变量的任何更改。
使用React的useState钩子来管理游戏状态。
将 API 调用和游戏逻辑移至单独的函数中。
使用useState提供的setState函数更新状态。
在 play 函数中,我们使用 setGameState 根据 API 响应更新状态:
setGameState(prevState => {
let newState = { ...prevState };
// Update newState based on the result
return newState;
});
import './App.css';
import React, { useState, useRef } from 'react';
const { OpenAI } = require('openai');
const openai = new OpenAI({ apiKey: '[myKey]' });
function App() {
const inputRef = useRef();
const [gameState, setGameState] = useState({
currentPerson: "Donald Trump",
count: 0
});
const people = ["Donald Trump", "Taylor Swift"];
const handleSubmit = async (event) => {
event.preventDefault();
const guess = inputRef.current.value;
await play(guess, gameState.currentPerson, people[1]);
}
async function play(guess, currentPerson, finalPerson) {
try {
const completion = await openai.chat.completions.create({
messages: [
{
role: "system",
content: "respond with true or false in lower case depending on if these people have met"
},
{
role: "user",
content: `${currentPerson}, ${guess}`
},
],
model: "gpt-4",
});
const result = completion.choices[0].message.content;
setGameState(prevState => {
let newState = { ...prevState };
if (result === "true" && guess === finalPerson) {
console.log("You Win!");
newState.count++;
} else if (result === "true") {
console.log("Correct");
newState.count++;
newState.currentPerson = guess;
} else {
console.log("Wrong");
}
console.log(newState);
return newState;
});
} catch (error) {
console.error("Error calling OpenAI API:", error);
}
}
return (
<form onSubmit={handleSubmit} >
<label>
Name:
<input name="guessInput" type="text" ref={inputRef} />
</label>
<button type="submit">
Submit
</button>
</form>
);
}
export default App;
https://react.dev/learn/state-a-components-memory#adding-a-state-variable