包装在UseEffect中的React异步函数 [英] React Async Function wrapped in a UseEffect
问题描述
我对异步功能的工作方式感到困惑.
I am confused on how an async function works.
console.log返回错误,因为data.rates尚不存在.但是我认为,因为useEffect函数是异步函数,所以异步结束后将调用其下的任何内容.
The console.log returns an error because the data.rates does not exist yet. But I thought because the useEffect function is async anything under it would be called after the async is over.
function App() {
const [data, setData] = useState();
useEffect(() => {
(async () => {
const result = await axios.get(
"https://open.exchangerate-api.com/v6/latest"
);
setData(result.data);
})();
}, []);
console.log(data.rates); <-- Error data.rates does not exist
return <div>{!data ? "Loading..." : "Hello"}</div>;
}
推荐答案
您的假设实际上是正确的,这种情况下的useEffect将在组件已安装时运行,这意味着 console.log
将被调用两次-第一个是初始值(未定义),第二个是在useEffect执行完请求后实际设置数据(setData)后产生的副作用.您通常会在数据过时的情况下提供正在加载"状态.
Your assumption is actually correct, useEffect in this scenario will run when the Component is mounted that means console.log
will be called twice--first with initial value (which is undefined), second is after useEffect performed the side-effect when data is actually set (setData) after the request is fulfilled. You would typically provide a "loading" state while data is stale.
function App() {
const [loading, setLoading] = useState(false);
const [data, setData] = useState();
useEffect(() => {
(async () => {
setLoading(true);
const result = await axios.get(
"https://open.exchangerate-api.com/v6/latest"
);
setLoading(false);
setData(result.data);
})();
}, []);
if (loading) return <div>Fetching data...</div>
return <div>Hello</div>;
}
这篇关于包装在UseEffect中的React异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!