我正在尝试使用useEffect来获取数据,但是当单击路由器链接时,首先要获取数据,然后打开page / comp。因此,这会导致页面加载缓慢。我该如何首先打开组件,加载gif以及对数据进行加脂处理?
注意:我正在使用jsonplaceholder的照片api。有5k张照片数据。
上下文
const PhotosCtx = React.createContext();
const initialState = {
photos:[],
isLoading:true
}
const PhotoProvider = props => {
const [Photos, setPhotos] = useState(initialState)
const values = Photos;
useEffect(()=>{
const fetchPhoto = async () => {
const getPhotos = await axios.get('https://jsonplaceholder.typicode.com/photos')
setPhotos({
photos:getPhotos.data,
isLoading:false
});
}
fetchPhoto()
}, [])
return(
<PhotosCtx.Provider value={values}>
{props.children}
</PhotosCtx.Provider>
)
}
export {PhotosCtx, PhotoProvider}
Photos.js
const Photos = () => {
const value = useContext(PhotosCtx);
return (
<div className="container mt-5">
{value.isLoading ? (
<div className="text-center">
<div className="spinner-border" role="status">
<span className="sr-only">Loading...</span>
</div>
</div>
) : (
""
)}
<div className="row">
{value.photos.map((photo, index) => {
return (
<div key={index} className="col-4 mt-3">
<div className="card" style={{ width: "18rem" }}>
<div className="card-body">
<h5 className="card-title">{photo.albumId}</h5>
<h6 className="card-subtitle mb-2 text-muted">
{photo.title}
</h6>
<p className="card-text">{photo.url}</p>
<a href="#!" className="card-link">
{photo.thumbnailUrl}
</a>
</div>
</div>
</div>
);
})}
</div>
</div>
);
};