我查了一些问题,但没能解决这个问题。我正在尝试将 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;
答案 0 :(得分:1)
这是异步等待的方法。你试过这个吗?
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import SanityClient from "sanity.client";
const AllPosts = () => {
const [posts, setPosts] = useState(null);
const fetchData = async (postsQuery) => {
try {
const data = await SanityClient.fetch(postsQuery);
if (data) {
setPosts(data);
}
} catch(error) {
console.log(error);
}
}
useEffect(() => {
const postsQuery = `
*[_type == 'post'] {
_id,
title,
slug,
mainImage {
alt,
asset -> {
_id,
url
}
}
}
`;
fetchData(postsQuery);
}, []);
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;