在几个fetch函数上使用useEffect会导致它们在单击按钮之前运行,我如何使用useCallback来代替?<



我正在使用一个获取函数来在按下按钮后生成输出,然后在几个类似的获取函数中使用该输出。为了做到这一点,我使用了useEffect,但问题是这些第二和第三个函数在我按下按钮之前运行,按钮点击启动第一个获取函数,一旦这个运行,我只希望其他函数运行。否则,如果页面一加载就出现这些广告,我就要花很多钱。

我知道我应该使用useCallback,但简单地用useCallback代替useEffect当然不起作用,因为它只在某事完成时运行。我试图用useCallBack替换第二和第三个函数中的异步函数,如下所示:

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状态,因此它们需要等待按钮完成。

是否有一个解决方案,不运行第二和第三个功能在后台?

添加if条件,当输入有值时运行调用

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

最新更新