无法使用Apollo-link-rest和ReactJS从数组中渲染嵌套对象

时间:2019-04-24 23:24:31

标签: reactjs apollo-link-rest

尝试获取嵌套数据downloads.copy以便在页面上呈现。我可以使用Apollo Client Dev Tools看到数据,但不会呈现到页面上。我搜索了apollo-link-rest问题。我确定这是语法问题-还是没有。任何帮助/见解将不胜感激。

import React, { Component } from "react";
import { graphql } from "react-apollo";
import gql from "graphql-tag";

const Query = gql`
  query tool {
    tools @rest(type: "ToolsPayload", path: "some-api/tools") {
      id
      headerTitle
      description
      downloads @type(name: "ToolsPayloadDownloads") {
        copy
      }
    }
  }
`;

class Tool extends Component {
  render() {
    const { loading, error, tools } = this.props;
    if (loading) {
      return <h4>Loading...</h4>;
    }
    if (error) {
      return <h4>{error.message}</h4>;
    }
    return (
      <div>
        {tools.map(tool => {
          return (
            <div key={tool.id}>
              <h1>{tool.headerTitle}</h1>
              // ** CAN'T GET THE DOWNLOADS COPY TO RENDER ** // 
              <h1>{tool.downloads.copy}</h1>
            </div>
          );
        })}
      </div>
    );
  }
}

export default graphql(Query, {
  props: ({ data }) => {
    if (data.loading) {
      return {
        loading: data.loading
      };
    }
    if (data.error) {
      return {
        error: data.error
      };
    }
    return {
      tools: data.tools,
      loading: false
    };
  }
})(Tool);

{
   [
      {
        "id": "1025",
        "headerTitle": "Title",
        "downloads": [
            {
                "id": "1234",
                "copy": "Some copy",

            }
        ]
    }, 
      {
        "id": "1026",
        "headerTitle": "Title2",
        "downloads": [
            {
                "id": "5678",
                "copy": "Some copy2",

            }
        ]
    },

  ]
}

1 个答案:

答案 0 :(得分:1)

downloads是一个数组-使用tool.downloads[0].copy

查询应在id中包含一个downloads字段-以正确地缓存ToolsPayloadDownloads类型。

您可以使用react开发工具来检查/检查apollo缓存数据/细节。