簡體   English   中英

在多個獲取函數上使用 useEffect 會導致它們在單擊按鈕之前運行,我該如何改用 useCallback?

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

按下按鈕后,我使用提取 function 生成 output,然后將此 output 用於幾個類似的提取功能。 為此,我使用了 useEffect,但問題是這些第二和第三個函數在我按下按鈕之前運行,單擊按鈕會啟動第一次提取 function,一旦運行,我只會希望其他函數運行。 否則,如果它們在頁面加載后立即打開,那將花費我很多錢。

我知道我應該使用 useCallback,但是簡單地用 useCallback 替換 useEffect 當然是行不通的,因為它只在某些事情完成時運行。 我嘗試用 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]);

但是這不起作用,它生成的 Story 不是基於 inputName - 它假定 inputName 為空。

這是我使用 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}>

一旦我點擊按鈕,一切都安定下來,但在我點擊它之前,inputStory 和 inputDescription 一直在后台運行。 我只希望它們在單擊按鈕后運行,但我需要它們依賴於 inputName state,因此它們需要等待它完成。

有沒有不在后台運行第二個和第三個功能的解決方案?

添加一個 if 條件以在輸入有值時運行調用

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

}, [inputName])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM