【问题标题】:React useAsync() not receive a data that return from fetchData()React useAsync() 没有收到从 fetchData() 返回的数据
【发布时间】: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 对我来说很容易理解(其他方式也是错误)

【问题讨论】:

    标签: reactjs react-tsx


    【解决方案1】:

    现在我从朋友那里得到了解决方案,使用 state 和 useEffect 而不是 useAsync

    const [isLoaded, setIsloaded] = React.useState<boolean | null>(false);
    React.useEffect(() => {
            const fetchData = async () => {
                await getUser();
                await getGender();
                await getStorage();
                await getGame();
                setIsloaded(true);
            }
            fetchData();
        }, []);
    
        if (isLoaded) return(//render)
    

    【讨论】:

      猜你喜欢
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 2015-06-11
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多