如何在加载fetch之前显示加载消息



我有一个从API加载的项列表。如果没有项目,我应该看到一条消息,说明当前没有可用的项目。现在的情况是,在加载项目时,此消息会显示一两秒钟。所以我的问题是:我如何显示例如";正在加载项目"而不是其他消息,直到我的所有项目都呈现出来?

import React,{useState, useEffect} from "react";
import Item from '../components/Item'
function Deals() {
const [items, setItems] = useState([])
const [isLoading, setIsLoading] = useState(true)
useEffect(async () => {
const response = await fetch("https://gp-super-store-api.herokuapp.com/item/list")
const data = await response.json()
setItems(data.items)
setIsLoading(false)
}, [])
const filter = items.filter((item) => item.isOnSale === true)
if(filter.length === 0){
return <h1>Sorry folks, nothing for sale today :(</h1>
}

return (
<div>
{items.filter((item) => item.isOnSale === true).map((item) => (
<Item 
name={item.name} 
img={item.imageUrl} 
price={"$" + item.price}
onsale={item.isOnSale}
starsNum={item.avgRating}
stock={item.stockCount}
id={item._id}
/>
))}
</div>
);
}
export default Deals;

您可以使用设置的加载状态进行有条件的渲染。

import React,{useState, useEffect} from "react";
import Item from '../components/Item'
function Deals() {
const [items, setItems] = useState([])
const [isLoading, setIsLoading] = useState(true)
useEffect(async () => {
const response = await fetch("https://gp-super-store-api.herokuapp.com/item/list")
const data = await response.json()
setItems(data.items)
setIsLoading(false)
}, [])
const filter = items.filter((item) => item.isOnSale === true)
if(filter.length === 0){
return <h1>Sorry folks, nothing for sale today :</h1>
}
return (
<>
{ loading? "Loading items...":(
<div>
{items.filter((item) => item.isOnSale === true).map((item) => (
<Item 
name={item.name} 
img={item.imageUrl} 
price={"$" + item.price}
onsale={item.isOnSale}
starsNum={item.avgRating}
stock={item.stockCount}
id={item._id}
/>
))}
</div> )}

</>
);
}
export default Deals;

相关内容

  • 没有找到相关文章

最新更新