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

确保故事状态更新后调用 fetchMovieDescription 函数

聖光之護
发布: 2025-10-03 13:34:02
原创
765人浏览过

确保故事状态更新后调用 fetchmoviedescription 函数

本文旨在解决 React 应用中 fetchMovieDescription 函数在故事状态更新后未能正确调用的问题。通过分析问题代码,我们发现 useEffect 的依赖项设置不合理,导致函数在故事状态更新前就被触发。本文将提供修改后的 useEffect 代码,确保 fetchMovieDescription 函数仅在故事状态更新后执行,从而避免生成错误的图片。

问题分析

原始代码中,useEffect 依赖于 storyFetched 状态,该状态在 fetchBotReply 函数中被设置为 true,但由于 React 的状态更新是异步的,可能导致 fetchMovieDescription 函数在 story 状态更新前就被调用,从而使用了旧的或空的故事内容。

解决方案

为了确保 fetchMovieDescription 函数仅在 story 状态更新后调用,我们需要在 useEffect 中添加条件判断,只有当 storyFetched 为 true 时才执行 fetchMovieDescription 函数。

新CG儿
新CG儿

数字视觉分享平台 | AE模板_视频素材

新CG儿 147
查看详情 新CG儿
useEffect(() => {
  if (storyFetched) {
    fetchMovieDescription(story);
  }
}, [storyFetched]);
登录后复制

代码解释

  • useEffect(() => { ... }, [storyFetched]);: 这是一个 React Hook,用于在组件渲染后执行副作用操作。[storyFetched] 指定了只有当 storyFetched 状态发生改变时,useEffect 中的函数才会执行。
  • if (storyFetched) { ... }: 这是一个条件判断语句。只有当 storyFetched 为 true 时,才会执行 if 语句块中的代码。
  • fetchMovieDescription(story);: 调用 fetchMovieDescription 函数,并将 story 作为参数传递给它。

完整代码示例

以下是包含修改后的 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>
    )
}
登录后复制

注意事项

  • 确保 storyFetched 状态在 story 状态更新后被设置为 true。
  • 如果 fetchMovieDescription 函数仍然在 story 状态更新前被调用,请检查 fetchBotReply 函数中 setStoryFetched(true) 的位置是否正确。
  • 可以考虑使用 useRef 来保存 story 的最新值,并在 useEffect 中使用 useRef 的 current 属性来获取最新的 story 值。

总结

通过在 useEffect 中添加条件判断,我们可以确保 fetchMovieDescription 函数仅在 story 状态更新后被调用,从而避免生成错误的图片。这种方法可以有效地解决 React 应用中异步状态更新导致的问题。理解 useEffect 的依赖项和状态更新的机制对于编写高质量的 React 代码至关重要.

以上就是确保故事状态更新后调用 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号