简体   繁体   English

在多个获取函数上使用 useEffect 会导致它们在单击按钮之前运行,我该如何改用 useCallback?

[英]Using useEffect on several fetch functions causes them to run before a button click, how do I use useCallback instead?

I am using a fetch function to generate an output after pressing a button, this output is then used in several similar fetch functions.按下按钮后,我使用提取 function 生成 output,然后将此 output 用于几个类似的提取功能。 To do this I've used useEffect, but the issue is these 2nd and 3rd functions run before I press the button, the button click initiates the first fetch function and once this runs I would only then like the others to run.为此,我使用了 useEffect,但问题是这些第二和第三个函数在我按下按钮之前运行,单击按钮会启动第一次提取 function,一旦运行,我只会希望其他函数运行。 Otherwise it costs me a lot of money if they're on as soon as the page loads.否则,如果它们在页面加载后立即打开,那将花费我很多钱。

I know I should use useCallback, but simply replacing useEffect with useCallback doesn't work of course because it only runs when something is completed.我知道我应该使用 useCallback,但是简单地用 useCallback 替换 useEffect 当然是行不通的,因为它只在某些事情完成时运行。 I tried to replace the async function in the 2nd and 3rd functions with useCallBack, like so:我尝试用 useCallBack 替换第二个和第三个函数中的异步 function,如下所示:

    const getOpenAIResponse = async () => {
        openai.createCompletion({
            model: "text-davinci-003",
            prompt: "Create a unique 1-5 word name.",
            max_tokens: 256,
        }).then((response) => {
            setInputName(response.data.choices[0].text)
            getSlogan()
        })
    };

    const getStory = useCallback (() => {
        openai.createCompletion({
            model: "text-davinci-003",
            prompt: "Create a story about " + inputName + ".",
            max_tokens: 256,
        }).then((response) => {
            setInputStory(response.data.choices[0].text)
        })
        }, [inputName]);

However this did not work, the Story it produced was not based on the inputName - it assumed inputName was blank.但是这不起作用,它生成的 Story 不是基于 inputName - 它假定 inputName 为空。

This is my code with useEffect.这是我使用 useEffect 的代码。

    const [inputName, setInputName] = useState('');
    const [inputStory, setInputStory] = useState('');
    const [inputDes, setInputDes] = useState('');

    const getOpenAIResponse = async () => {
        openai.createCompletion({
            model: "text-davinci-003",
            prompt: "Create a unique 1-5 word name.",
            max_tokens: 256,
        }).then((response) => {
            setInputName(response.data.choices[0].text)
        })
    };

    const getStory = async () => {
        openai.createCompletion({
            model: "text-davinci-003",
            prompt: "Create a story about " + inputName + ".",
            max_tokens: 256,
        }).then((response) => {
            setInputStory(response.data.choices[0].text)
        })
    };

    const getDescription = async () => {
        openai.createCompletion({
            model: "text-davinci-003",
            prompt: "Create a description for " + inputName + ".",
            max_tokens: 256,
        }).then((response) => {
            setInputDes(response.data.choices[0].text)
        })
    };

    useEffect(() => {
        getStory();
        getDescription();
    }, [inputName]);


<Button onClick={getOpenAIResponse}>

Once I click the button everything settles down, but before I click it the inputStory and inputDescription are continously running in the background.一旦我点击按钮,一切都安定下来,但在我点击它之前,inputStory 和 inputDescription 一直在后台运行。 I only want them to run once the button is clicked, but I need them to depend on the inputName state, so they need to wait for it to finish.我只希望它们在单击按钮后运行,但我需要它们依赖于 inputName state,因此它们需要等待它完成。

Is there a solution that doesn't run the 2nd and 3rd functions in the background?有没有不在后台运行第二个和第三个功能的解决方案?

add a if condition to run the calls when input has values添加一个 if 条件以在输入有值时运行调用

useEffect(() => {
  if(inputName){    
    getStory();
    getDescription();
  }

}, [inputName])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在按钮单击时触发 useCallback、useMemo 或 useEffect? - How to trigger useCallback, useMemo or useEffect on button click? 如何在单个按钮单击事件上运行两个功能 - How do I run two functions on a single button click event 如何在按钮点击上使用useEffect? - How to use useEffect on button Click? 如何在 svelte 中使用 useCallback 钩子 - how do I use useCallback hook in svelte React useEffect 导致函数运行 7 次。 我正在使用 useCallback 但它仍然运行很多次 - React useEffect causing function to run 7 times. I am using a useCallback but it still runs to many times 如何在按钮单击时使用 useEffect 行为 - How to use useeffect behavior on button click jQuery如何在单击按钮后在具有其他功能之前延迟并删除和添加类 - Jquery how do i remove and add a class after button click with time delay before other functions 如何使用promise来链接几个setTimeout函数? - How do I use a promise to chain several setTimeout functions? 我正在使用反应钩子 useEffect 来获取建议 api。 每次刷新页面后它都会自动更改我如何使用按钮自动更改 - i'm using react hook useEffect to fetch an advice api. it changed automatically after every page refresh how can i do it automaticly using a button 如何使用 useMemo 或 useCallback 在 React 中防止不必要的重新渲染? - How do i prevent unnecessary rerendering in React using useMemo or useCallback?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM