使用嵌套对象获取 React 中 Graphql 的问题 - 对象未定义

Posted

技术标签:

【中文标题】使用嵌套对象获取 React 中 Graphql 的问题 - 对象未定义【英文标题】:Issue with Graphql in React fetching with a nested object - Object is undefined 【发布时间】:2021-09-10 22:34:22 【问题描述】:

当我用参数插入用户 ID 时更新,它可以工作,但不能 使用graphql fetch中的参数

后端在操场上使用 graphql,在前端 使用 Apollo 开发工具显示它已到达客户端。控制台日志 给出“GetUserId 未定义”

[仪表板 - 前端]

        import React from "react";
        import  useQuery  from "@apollo/react-hooks";
        import PostCard from "../../components/PostCard";
        import gql from graphql-tag;
       attempting to fetch data on the frontend
          export default function Dashboard() 
          const  loading, data  = useQuery(FETCH_POST_QUERY);
          if (loading) return <div>Loading...</div>;
          const  getUserPost: userId  = data;
    
  return (
    <div className="PostCard">
      <h1>Host Events</h1>
      userId.CreatedEvents.map((list) => (
        <PostCard
          //add img
          id=list.id
          key=list.id
          title=list.title
          description=list.description
          price=list.price
          address=list.address
          date=list.date
        />
      ))
    </div>
  );

从 graphql 获取 - 不确定格式是否正确

const FETCH_POST_QUERY = gql`
  query getUserPost($userId: ID!) 
    getUserPost(userId: $userId) 
      createdEvents 
        id
        address
        category
        date
        description
        price
        title
      
    
  
`;

[用户架构] - 嵌套的 createdEvents 有问题

const userSchema = new Schema(
  username: String,
  password: String,
  email: String,
  createdAt: String,
  createdEvents: [
    
      type: Schema.Types.ObjectId,
      ref: "Post",
    ,
  ],
);

module.exports = model("User", userSchema);
[Resolver] 
在后端工作
    async getUserPost(_,  userId ) 
      // Query into creator nested scheme
      const events = async (eventIds) => 
        try 
          const events = await Post.find( _id:  $in: eventIds  );
          return events.map((event) => 
            return 
              ...event._doc,
              id: event.id,
              creator: user.bind(this, event.creator),
            ;
          );
         catch (err) 
          throw err;
        
      ;

      const user = async (userId) => 
        try 
          const user = await User.findById(userId);
          return 
            ...user._doc,
            id: user.id,
            createdEvents: events.bind(this, user._doc.createdEvents),
          ;
         catch (err) 
          throw err;
        
      ;
      // Nested createdEvents
      const event = await User.findById(userId);
      return 
        ...event._doc,
        id: event.id,
        createdEvents: events.bind(this, event._doc.createdEvents),
      ;
    ,
  ,

【问题讨论】:

【参考方案1】:

您在 FETCH_POST_QUERY 中告诉将 userId 作为输入参数传递,它不能为空,但忘记从前端传递 userId。查询将如下所示:

      const  loading, data  = useQuery(FETCH_POST_QUERY,variables:userId:1);

【讨论】:

const getUserPost: userId = data; 没有数据时如何解构数据?需要 userId 作为输入参数才能获取数据 感谢尼泊尔的帮助,给你一颗星,但我是新手。【参考方案2】:
> Got it to work!

import React,  useContext  from "react";
import  useQuery  from "@apollo/react-hooks";
import PostCard from "../../components/PostCard";
import  AuthContext  from "../../context/auth";
import gql from "graphql-tag";

export default function Dashboard() 
  const context = useContext(AuthContext);
  const  loading, data  = 
  useQuery(FETCH_POST_QUERY, 
    variables:  userId: context.user.id ,
  );

  console.log(context.user);

  if (loading) return <div>Loading...</div>;

  const  getUserPost: userId  = data;

  return (
    <div className="PostCard">
      <h1>Host Events</h1>
      userId.createdEvents.map((list) => (
        <PostCard
          // Add img
          id=list.id
          key=list.id
          title=list.title
          description=list.description
          price=list.price
          address=list.address
          date=list.date
        />
      ))
    </div>
  );


// Query into a nested object -> User -> 
     CreatedEvents -> post
    const FETCH_POST_QUERY = gql`
    query getUserPost($userId: ID!) 
    getUserPost(userId: $userId) 
      createdEvents 
        id
        address
        category
        date
        description
        price
        title
      
    
  
`;

【讨论】:

以上是关于使用嵌套对象获取 React 中 Graphql 的问题 - 对象未定义的主要内容,如果未能解决你的问题,请参考以下文章

为嵌套模式 graphql/apollo/react 添加突变

GraphQL - 从嵌套的 JSON 对象中获取所有字段

Graphql Django 获取嵌套对象属性的最佳方法

React 如何在嵌套数据对象中渲染动态图像

Apollo/GraphQL:如何获取嵌套元素?

带有嵌套查询(Django + React)的 Graphql 瓶颈性能使前端应用程序无法使用。请帮忙 :'(