【问题标题】:TypeError: Cannot read properties of undefined using reactjs and graphqlTypeError:无法使用 reactjs 和 graphql 读取未定义的属性
【发布时间】:2022-01-12 20:19:24
【问题描述】:

我正在使用 RactJS、Mongoose、GraphQL 和 Apollo 创建一个社交媒体。当我尝试从数据库中获取数据以显示在主页中时,我收到一条错误消息:TypeError: Cannot read properties of undefined (reading 'getPosts')。我搜索解决方案并尝试了很多东西,但没有任何效果

文件结构

--客户

----node_modules

----公开

----src

------组件

--------MenuBar.js

--------PostCard.js

------页面

--------Home.js

--graphQL

----解析器

--------cmets.js

--------index.js

--------posts.js

--------users.js

----typeDefs.js

--模型

----Post.js

----用户.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;

posts.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')
        }
    }
}

当我 console.log(data) 在实现数据之前:{getPosts: posts} 它运行顺利,按预期返回了一个对象,但之后应用程序崩溃了。

【问题讨论】:

  • 缺少if(loading) return &lt;Loading /&gt; ...阅读文档
  • 来自 docs function Hello() { const { loading, error, data } = useQuery(GET_GREETING, { variables: { language: 'english' }, }); if (加载) 返回

    加载中 ...

    ;返回

    你好{data.greeting.message}!

    ;我确实有加载
  • 顺便说一句,我尝试了文档示例,但仍然遇到同样的错误

标签: reactjs mongodb graphql apollo


【解决方案1】:

也许试试这个:

const { loading, data } = useQuery(FETCH_POSTS_QUERY)
const { getPosts: posts } = {...data}

如果它仍然不起作用,请告诉我。在下面发表评论。

【讨论】:

    猜你喜欢
    • 2021-12-06
    • 2022-07-22
    • 2019-05-07
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    相关资源
    最近更新 更多