我正在开发一个组件,使用语义 UI 在客户端映射来自 graphQL 查询的所有帖子。我在本地运行它,即使此查询在 apollo studio 中工作,网页也没有显示任何数据。
这是该组件的代码。
import React from 'react';
import { useQuery } from '@apollo/client';
import { GET_POSTS } from '../utils/queries';
export const PostFeed = () => {
const { loading, data } = useQuery(GET_POSTS, {
fetchPolicy: "no-cache"
});
const posts = data?.post || [];
return (
<div>
<h1>Post feed</h1>
{loading ? (
<div>Loading...</div>
) : (
<div className="ui feed">
{posts.map((post) => {
return (
<div className="event post">
<div className="label">
{/* <img src={post.author.profilePic}/> */}
</div>
<div className="content">
<div className="summary">
<a className="user">
{post.postAuthor}
</a>posted on their page
<div className="date">
{/* {post.createdAt} */}
</div>
</div>
<div className="extra text">
{post.postText}
</div>
<div className="meta">
<a className="like">
{/* <i className="like icon"></i>{post.likes} */}
</a>
</div>
</div>
</div>
);
})}
</div>
)}
</div>
)
}
这是实用程序/查询代码:
import { gql } from '@apollo/client';
export const GET_POSTS = gql`
query GetPosts {
getPosts {
_id
postAuthor
postText
}
}
`;
我编写了以下代码以确保查询正在提取数据并且它确实返回正确的数据点(在屏幕截图中共享)。
const { loading, error, data } = useQuery(GET_POSTS);
if (loading) return "Loading...";
if (error) return `Error! ${error.message}`;
return (<div>{JSON.stringify(data)}</div>);
当您应该指
data.post
时,您指的是data.getPosts
。
尝试:
const posts = data?.getPosts || [];