
在 React 应用开发中,我们经常需要在特定状态改变后执行一些副作用操作,例如发起 API 请求。如果处理不当,可能会导致函数在不恰当的时机执行,产生意料之外的结果。本文将针对一个具体案例,讲解如何确保 fetchMovieDescription 函数在故事状态改变后才被调用。
正如摘要所述,问题的核心在于 useEffect 的依赖项设置。原代码中,useEffect 依赖于 storyFetched 状态,虽然尝试用它来控制 fetchMovieDescription 的调用时机,但由于逻辑上的问题,导致函数依然会在故事状态更新前被执行。
正确的做法是在 useEffect 内部添加条件判断,只有当 storyFetched 为 true 时,才调用 fetchMovieDescription 函数。
以下是修正后的 useEffect 代码:
useEffect(() => {
if (storyFetched) {
fetchMovieDescription(story);
}
}, [storyFetched]);这段代码的作用是:
通过这种方式,我们确保了 fetchMovieDescription 函数仅在故事状态被成功获取并更新后才会执行。
注意事项:
完整示例代码:
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 中添加条件判断,我们可以精确控制副作用函数的执行时机,确保它们仅在特定状态满足条件时才被调用。这是一种常用的 React 开发技巧,可以避免很多潜在的问题,提高代码的健壮性和可维护性。在处理异步操作和状态更新时,务必仔细考虑 useEffect 的依赖项和执行逻辑,确保代码的行为符合预期。
以上就是确保在故事状态改变后调用 fetchMovieDescription 函数的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号