首页 > web前端 > js教程 > 正文

确保在故事状态改变后调用 fetchMovieDescription 函数

霞舞
发布: 2025-10-03 08:52:01
原创
999人浏览过

确保在故事状态改变后调用 fetchmoviedescription 函数

在 React 应用开发中,我们经常需要在特定状态改变后执行一些副作用操作,例如发起 API 请求。如果处理不当,可能会导致函数在不恰当的时机执行,产生意料之外的结果。本文将针对一个具体案例,讲解如何确保 fetchMovieDescription 函数在故事状态改变后才被调用。

正如摘要所述,问题的核心在于 useEffect 的依赖项设置。原代码中,useEffect 依赖于 storyFetched 状态,虽然尝试用它来控制 fetchMovieDescription 的调用时机,但由于逻辑上的问题,导致函数依然会在故事状态更新前被执行。

正确的做法是在 useEffect 内部添加条件判断,只有当 storyFetched 为 true 时,才调用 fetchMovieDescription 函数。

以下是修正后的 useEffect 代码:

useEffect(() => {
  if (storyFetched) {
    fetchMovieDescription(story);
  }
}, [storyFetched]);
登录后复制

这段代码的作用是:

  1. useEffect 会在 storyFetched 状态发生变化时触发。
  2. 在 useEffect 的回调函数内部,使用 if (storyFetched) 判断 storyFetched 的值是否为 true。
  3. 只有当 storyFetched 为 true 时,才会调用 fetchMovieDescription(story) 函数。

通过这种方式,我们确保了 fetchMovieDescription 函数仅在故事状态被成功获取并更新后才会执行。

图改改
图改改

在线修改图片文字

图改改 455
查看详情 图改改

注意事项:

  • 确保 setStoryFetched(true) 在 fetchBotReply 函数中,setStory(response.data.choices[0].text) 之后被调用。
  • 如果 story 状态的更新也会触发 useEffect,并且在某些情况下需要在 storyFetched 为 false 时执行一些操作,则需要添加额外的判断逻辑。

完整示例代码:

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中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号