如何在 REACT JS 中通过 fetch api 从服务器加载数据时显示微调器?

问题描述 投票:0回答:3

我正在开发一个 React 应用程序,我必须从主页上的服务器加载数据。从服务器加载数据需要少量时间。我想在调用 fetch api 时显示一个微调器。我已经创建了一个微调器组件,但我不知道如何在触发 fetch api 时显示该微调器。

const [product,setProduct]=useState({});
useEffect(()=>{
    fetch(`http://localhost:5000/readSingleCarsData/${id}`)
    .then(res=>res.json())
    .then(data=> {
        setProduct(data)
        setQuantity(data.quantity)
    });
},[])
reactjs spinner loading
3个回答
3
投票

用钩子控制你的加载器状态,并使用

.finally()
将你的加载状态转换回 false。

import { useEffect, useState } from 'react';

export default function Home() {
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        setLoading(true);
        fetch('/api/hello')
            .then((res) => res.json())
            .then((data) => {
                // do something with data
            })
            .catch((err) => {
                console.log(err);
            })
            .finally(() => {
                setLoading(false);
            });
    }, []);

    if (loading) {
        return <LoadingComponent />;
    }

    return <MyRegularComponent />;
}

1
投票
const [product,setProduct]=useState({})
const [isLoading, setLoading]=useState(false);

useEffect(()=>{
    setLoading(true);
    fetch(`http://localhost:5000/readSingleCarsData/${id}`)
    .then(res=>res.json())
    .then(data=> {
        setProduct(data)
        setQuantity(data.quantity)
        setLoading(false);
    });
},[]);

return isLoading ? <Spiner /> : <Component />

试试这个


0
投票

通过使用

react-suspense-render-hook
,您可以轻松实现基于数据处理的组件渲染。尝试一下

import { useState, useCallback } from 'react';
import { useSuspenseRender } from 'react-suspense-render-hook';

const Component = () => {
    const [product, setProduct] = useState({});
    const fetcher = useCallback(async () => {
        const data = await fetch(`http://localhost:5000/readSingleCarsData/${id}`);
        setProduct(data);
    }, []);

    const [suspenseRender] = useSuspenseRender(fetcher);    

    return suspenseRender(
        <div>Success</div>,
        <div>Loading...</div>,
        <div>Failure</div>,
    );
}
© www.soinside.com 2019 - 2024. All rights reserved.