简体   繁体   English

在反应中获取数据之前如何添加加载微调器?

[英]How can i add loading spinner before fetching data in react?

What is the correct way to add a spinner while fetching data from API in react js?在 react js 中从 API 获取数据时添加微调器的正确方法是什么? I tried to display the spinner until the data.length > 0 it works fine when the data is more than zero.我尝试显示微调器直到data.length > 0当数据大于零时它工作正常。 But when it is actually zero, the loading spinner doesn't stop.但是当它实际上为零时,加载微调器不会停止。 Is there any good solution for this?对此有什么好的解决方案吗?

You didn't provide enough info or code to tell exactly what to do but i will give you a simple example你没有提供足够的信息或代码来确切地告诉你该怎么做,但我会给你一个简单的例子

just create a state for the loading set it true and when the fetch is done set it false只需为加载创建一个 state 将其设置为 true 并在获取完成后将其设置为 false

I hope this example is clear我希望这个例子很清楚

import { useEffect,useState } from 'react'

export default function Page() {
    const [data, setData] = useState(null)
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        fetch('/api/test',{method: 'GET'})
        .then(res => res.json())
        .then(data => {
            console.log(data)
            setData(data)
        }
        )
        .catch(err => {
            console.log(err)
        }
        )
        .finally(() => {
            setLoading(false)
        })
    }, [])
    if(loading) return <div>Loading...</div> // or your loading spinner
    return (
    <div>{JSON.stringify(data)}</div>
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从数据库中获取项目时如何添加 React 加载微调器? - How can i add React loading spinner when item is fetching from database? React-query:在获取数据时显示加载微调器 - React-query: Show loading spinner while fetching data 如何在按钮 onlick 上添加加载微调器 - How can I add loading spinner on button onlick 如何仅在数据之前加载微调器 - How can I have the spinner load only before the data 在另一个屏幕上从该数据库中获取数据之前,我如何才能等到数据在一个屏幕中添加到数据库中? (反应原生,Firebase) - How can I wait until data is added to a database in one screen before fetching the data from that database on another screen? (React Native, Firebase) 在获取数据时显示加载微调器 - Display Loading spinner whilst data is fetching 如何在 React App 完成加载之前显示整页加载器/微调器 - How to show fullpage loader/spinner before React App finish loading 如何添加加载“微调器” - how to add a loading “spinner” 使用服务从数据库中获取数据时,如何显示和隐藏简单的CSS微调器-Angular 2&gt; - How can I show & hide simple CSS spinner while fetching data from database with my service - Angular 2> 在加载所有资产之前,如何添加加载效果? - How can I add a loading effect before all assets are loaded?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM