【发布时间】:2021-06-06 21:05:37
【问题描述】:
我查找了一些问题,但未能解决此问题。我正在尝试将async and await 添加到我正在获取数据的useEffect 中。
另外,如何在先加载数据之前添加一个简单的加载文本?
我的代码:
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import SanityClient from "sanity.client";
const AllPosts = () => {
const [posts, setPosts] = useState(null);
useEffect(() => {
const postsQuery = `
*[_type == 'post'] {
_id,
title,
slug,
mainImage {
alt,
asset -> {
_id,
url
}
}
}
`;
SanityClient.fetch(postsQuery)
.then((data) => setPosts(data))
.catch(console.error);
}, []);
return (
<>
<h2>Blog Posts</h2>
<h3>Welcome to my blog</h3>
{posts &&
posts.map((post) => (
<Link key={post._id} to={`/blog/${post.slug.current}`}>
<img src={post.mainImage.asset.url} alt={post.mainImage.alt} />
<h2>{post.title}</h2>
</Link>
))}
</>
);
};
export default AllPosts;
【问题讨论】:
-
你在等待什么?你已经在使用 Promise 链了。