[英]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.