【发布时间】:2023-01-02 19:50:49
【问题描述】:
我想在加载组件之前从服务器加载数据。
const fecthData = async () => {
const apiUrl = "http://localhost:8080/user/natt@gmail.com";
const requestOptions = {
method: "GET",
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
"Content-Type": "application/json",
},
};
const res = await fetch(apiUrl, requestOptions);
if (!res.ok) throw new Error(res.statusText);
console.log(res.json());
return res.json();
}
const { data, error, isLoading } = useAsync({ promiseFn: fecthData });
console.log(data)
if (isLoading) return <Grid>"Loading..."</Grid>;
if (error) return <Grid>Something went wrong: {`${error.message}`}</Grid>;
if (data) return(<Grid>"main code"</Grid>)
console.log(res.json());是从服务器正确返回数据,但数据变量在
const { data, error, isLoading } = useAsync({ promiseFn: fecthData });
未定义
我尝试了很多其他方式,useAsync 对我来说很容易理解(其他方式也是错误)
【问题讨论】: