
本文旨在解决 React 应用中 fetchMovieDescription 函数在故事状态更新后未能正确调用的问题。通过分析问题代码,我们发现 useEffect 的依赖项设置不合理,导致函数在故事状态更新前就被触发。本文将提供修改后的 useEffect 代码,确保 fetchMovieDescription 函数仅在故事状态更新后执行,从而避免生成错误的图片。
原始代码中,useEffect 依赖于 storyFetched 状态,该状态在 fetchBotReply 函数中被设置为 true,但由于 React 的状态更新是异步的,可能导致 fetchMovieDescription 函数在 story 状态更新前就被调用,从而使用了旧的或空的故事内容。
为了确保 fetchMovieDescription 函数仅在 story 状态更新后调用,我们需要在 useEffect 中添加条件判断,只有当 storyFetched 为 true 时才执行 fetchMovieDescription 函数。
useEffect(() => {
if (storyFetched) {
fetchMovieDescription(story);
}
}, [storyFetched]);以下是包含修改后的 useEffect 的完整代码示例:
import { process } from '../env'
import { Configuration, OpenAIApi } from 'openai'
import { useState, useEffect } from 'react'
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY
})
const openai = new OpenAIApi(configuration)
export default function StoryPart() {
const [userInput, setUserInput] = useState("")
const [story, setStory] = useState("")
const [images, setImages] = useState("")
const [storyFetched, setStoryFetched] = useState(false);
useEffect(() => {
if (storyFetched) {
fetchMovieDescription(story);
}
}, [storyFetched])
const handleChange = (event) => {
setUserInput(event.target.value);
}
const handleSubmit = async (event) => {
event.preventDefault();
await fetchBotReply(userInput);
setUserInput("");
}
async function fetchBotReply(userInput) {
try {
const response = await openai.createCompletion({
model: 'text-davinci-003',
prompt: `You are an AI developed by OpenAI.
You have been trained on a vast range of internet text.
But unlike most AI models, your specialty is in creating unique and compelling movie scenarios.
You understand the elements of a great movie, including plot development, character arcs, conflict, and resolution.
You can generate scenarios in any genre, time period, or setting.
Your task is to write a scenario based on: ${userInput}.You must create the scenario so its easy to split it into 5
sections.The reason for it is that based on each section i will later ask you to write 5 detailed descriptions
of an image for later image generation.`,
max_tokens: 700,
temperature: 1
})
setStory(response.data.choices[0].text)
setStoryFetched(true)
} catch (error) {
console.log(error)
}
}
async function fetchMovieDescription(story) {
try {
const response = await openai.createImage({
prompt: `Create a descriptive and precise prompt for image generation based on this story: ${story}`,
n: 1,
size: "512x512",
response_format: 'url'
})
console.log(story)
setImages(response.data.data[0].url)
console.log(response.data.data[0].url)
} catch (error) {
console.log(error)
}
}
return (
<div className="StoryPart">
<form onSubmit={handleSubmit}>
<label>
Story:
<input value={userInput} type="text" name="story" placeholder='input prompt' onChange={handleChange}/>
</label>
<button type="submit" value="Submit">Submit</button>
</form>
{story? <p>{story}</p> : "Writing your story..."}
{images? <img src={images} alt="movie scene"/> : "Writing your images..."}
</div>
)
}通过在 useEffect 中添加条件判断,我们可以确保 fetchMovieDescription 函数仅在 story 状态更新后被调用,从而避免生成错误的图片。这种方法可以有效地解决 React 应用中异步状态更新导致的问题。理解 useEffect 的依赖项和状态更新的机制对于编写高质量的 React 代码至关重要.
以上就是确保故事状态更新后调用 fetchMovieDescription 函数的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号