我使用一个fetch函数在按下按钮后生成一个输出,然后在几个类似的提取函数中使用这个输出。要做到这一点,我使用了useEffect,但问题是在我按下按钮之前运行了第二个和第三个函数,单击按钮启动第一个获取函数,一旦运行,我只希望其他函数运行。否则,如果页面一打开,我就花了很多钱。
我知道我应该使用useCallback,但是用useCallback替换useEffect当然不起作用,因为它只在完成某件事情时才运行。我试图用useCallBack替换第2和第3个函数中的异步函数,如下所示:
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]);然而,这是行不通的,它产生的故事不是基于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状态,因此它们需要等待按钮完成。
是否有一种解决方案在后台不运行第二和第三个函数?
发布于 2022-12-02 16:54:28
添加一个if条件,以便在输入有值时运行调用
useEffect(() => {
if(inputName){
getStory();
getDescription();
}
}, [inputName])https://stackoverflow.com/questions/74659007
复制相似问题