如何在React中的UseEffect()中调用异步函数? [英] How to call an async function inside a UseEffect() in React?
问题描述
我想调用一个异步函数并获取UseEffect的结果.
I would like to call an async function and get the result for my UseEffect.
我在Internet上找到的fetch api示例是直接在useEffect函数中创建的. 如果我的网址更改了,我必须修补所有提取的内容.
The fetch api examples i found on the internet are directly made in the useEffect function. If my URL changes, i must patch all my fetchs.
当我尝试时,我收到一条错误消息.
When i tried, i got an error message.
这是我的代码.
async function getData(userId) {
const data = await axios.get(`http://url/api/data/${userId}`)
.then(promise => {
return promise.data;
})
.catch(e => {
console.error(e);
})
return data;
}
function blabla() {
const [data, setData] = useState(null);
useEffect(async () => {
setData(getData(1))
}, []);
return (
<div>
this is the {data["name"]}
</div>
);
}
index.js:1375警告:效果函数除用于清理的函数外,不得返回任何其他内容. 看起来您编写了useEffect(async()=> ...)或返回了Promise.而是在您的效果中编写异步函数并立即调用它:
index.js:1375 Warning: An effect function must not return anything besides a function, which is used for clean-up. It looks like you wrote useEffect(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately:
useEffect(() => {
async function fetchData() {
// You can await here
const response = await MyAPI.getData(someId);
// ...
}
fetchData();
}, [someId]); // Or [] if effect doesn't need props or state
推荐答案
在效果内部创建一个异步函数,该函数等待getData(1)
结果然后调用setData()
:
Create an async function inside your effect that wait the getData(1)
result then call setData()
:
useEffect(() => {
const fetchData = async () => {
const data = await getData(1);
setData(data);
}
fetchData();
}, []);
这篇关于如何在React中的UseEffect()中调用异步函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!