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

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

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

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

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

以下是修正后的 useEffect 代码:

useEffect(() => {  if (storyFetched) {    fetchMovieDescription(story);  }}, [storyFetched]);

这段代码的作用是:

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

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

注意事项:

确保 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 (        
{story?

{story}

: "Writing your story..."} {images? @@##@@ : "Writing your images..."}
);}

总结:

通过在 useEffect 中添加条件判断,我们可以精确控制副作用函数的执行时机,确保它们仅在特定状态满足条件时才被调用。这是一种常用的 React 开发技巧,可以避免很多潜在的问题,提高代码的健壮性和可维护性。在处理异步操作和状态更新时,务必仔细考虑 useEffect 的依赖项和执行逻辑,确保代码的行为符合预期。

movie scene

以上就是确保在故事状态改变后调用 fetchMovieDescription 函数的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1525740.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
TypeScript中的装饰器如何改变JavaScript的元编程能力?
上一篇 2025年12月20日 17:55:59
怎样构建一个基于 JavaScript 的跨平台桌面应用使用 Electron?
下一篇 2025年12月20日 17:56:09

相关推荐

发表回复

登录后才能评论
关注微信