我正在使用RactJS、Mongoose、GraphQL和Apollo创建一个社交媒体。当我试图从DB中获取要显示在主页中的数据时,我收到一个错误,说TypeError:无法读取未定义的属性(读取"getPosts"(。我搜索解决方案,尝试了一堆东西,但没有任何效果
文件结构
--客户端
----节点模块
----公共
----src
------组件
--------菜单栏.js
--------PostCard.js
------页面
--------Home.js
--graphQL
----解析器
--------comments.js
--------index.js
--------post.js
--------users.js
----typeDefs.js
--型号
----Post.js
----User.js
Home.js
import React from 'react';
import { useQuery } from '@apollo/react-hooks';
import gql from 'graphql-tag';
import { Grid } from 'semantic-ui-react';
import PostCard from '../components/PostCard';
function Home() {
const { loading, data: { getPosts: posts } } = useQuery(FETCH_POSTS_QUERY);
return (
<Grid columns={3}>
<Grid.Row>
<h1>Recent Posts</h1>
</Grid.Row>
<Grid.Row>
{loading ? (
<h1>Loading posts..</h1>
) : (
posts && posts.map(post => (
<Grid.Column key={post.id}>
<PostCard post={post} />
</Grid.Column>
))
)}
</Grid.Row>
</Grid>
)
}
const FETCH_POSTS_QUERY = gql`
{
getPosts{
id
body
createdAt
username
likeCount
likes {
username
}
commentCount
comments{
id
username
createdAt
body
}
}
}
`;
export default Home;
post.js
const { AuthenticationError, UserInputError } = require('apollo-server');
const Post = require('../../models/Post');
const checkAuth = require('../../util/check-auth');
module.exports = {
Query: {
async getPosts() {
try {
const posts = await Post.find().sort({ createdAt: -1 });
return posts;
} catch (err) {
throw new Error(err);
}
},
async getPost(_, { postId }) {
try {
const post = await Post.findById(postId);
if(post) {
return post;
} else {
throw new Error('Post not found')
}
} catch (err) {
throw new Error(err);
}
}
},
Mutation: {
async createPost(_, { body }, context) {
const user = checkAuth(context);
if(args.body.trim() === '') {
throw new Error('Post body must not be empty');
}
const newPost = new Post({
body,
user: user.id,
username: user.username,
createdAt: new Date().toISOString()
});
const post = await newPost.save();
context.pubsub.publish('NEW_POST', {
newPost: post
});
return post;
},
async deletePost(_, { postId }, context) {
const user = checkAuth(context);
try {
const post = await Post.findById(postId);
if(user.username === post.username) {
await post.delete();
return 'Post deleted successfully';
} else {
throw new AuthenticationError('Action not allowed');
}
} catch (err) {
throw new Error(err);
}
},
async likePost(_, { postId }, context) {
const { username } = checkAuth(context);
const post = await Post.findById(postId);
if (post) {
if (post.likes.find((like) => like.username === username)) {
// Post already likes, unlike it
post.likes = post.likes.filter((like) => like.username !== username);
} else {
// Not liked, like post
post.likes.push({
username,
createdAt: new Date().toISOString()
});
}
await post.save();
return post;
} else throw new UserInputError('Post not found');
}
},
Subscription: {
newPost: {
subscribe: (_, __, { pubsub }) => pubsub.asyncIterator('NEW_POST')
}
}
}
当我在实现data:{getPosts:posts}之前控制台.log(data(时,它运行得很顺利,按预期返回了一个对象,但之后应用程序崩溃了。
也许可以试试这个:
const { loading, data } = useQuery(FETCH_POSTS_QUERY)
const { getPosts: posts } = {...data}
或者另一种方法是:
const { loading, data: { getPosts: posts } = {} } = useQuery(FETCH_POSTS_QUERY)
如果它仍然不起作用,请告诉我,在下面留言。
而不是使用
const { loading, data: { getPosts: posts } } = useQuery(FETCH_POSTS_QUERY)
试试这个:
const { loading, data } = useQuery(FETCH_POSTS_QUERY)
const posts = data?.getPosts