【问题标题】:Map() function returning as undefined when attempting to return queryMap() 函数在尝试返回查询时返回未定义
【发布时间】:2020-01-10 06:11:28
【问题描述】:

我在从简单查询返回数据时遇到问题。我使用 Apollo 的测试应用程序 (https://codesandbox.io/s/nn9y2wzyw4) 正确执行了此操作,但是当我使用本地服务器中的数据尝试执行此操作时,它向我抛出 TypeError: Cannot read property 'map' of undefined。该查询显示在我的控制台日志和 GraphQL 操场上。

到目前为止,我发现返回数据的唯一方法是 map 函数,但我意识到它可能不适用于这种情况。我已经尝试以一百万种方式格式化我的退货声明,但似乎没有得到它。我知道这可能是一个非常简单的解决方案。

import React from "react";
import { render } from "react-dom";

import ApolloClient from "apollo-boost";
import { ApolloProvider, useQuery } from "@apollo/react-hooks";
import gql from "graphql-tag";

const client = new ApolloClient({
  uri: "http://localhost:4000/graphql"
});

function GetPokemon() {
  const { loading, error, data } = useQuery(gql`
    {
      pokemonById(id: "003") {
        id
        name
      }
    }
  `);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  console.log(data);

  return data.pokemonById.map((id, name) => (
    <div key={id}>
      <p>
        {id}: {name}
      </p>
    </div>
  ));
}

export const App = () => (
  <ApolloProvider client={client}>
    <div>
      <h2>My first Apollo app ????</h2>
      <GetPokemon />
    </div>
  </ApolloProvider>
);

有关更多上下文,我正在使用此 GraphQL 服务器的本地版本:https://github.com/axelhzf/graphql-pokemon-server

在操场上,我的查询如下所示:

{
  "data": {
    "pokemonById": {
      "id": "003",
      "name": "Venusaur"
    }
  }
}

【问题讨论】:

    标签: reactjs graphql jsx apollo


    【解决方案1】:

    您正在尝试在对象上使用地图。

      return  (
        <div key={id}>
          <p>
            {data.pokemonById.id}: {data.pokemonById.name}
          </p>
        </div>
      );
    

    【讨论】:

    • 啊当然。知道这是愚蠢的简单。谢谢。
    • 每个人都会遇到哈哈。只是有时需要一些新鲜的眼睛。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    相关资源
    最近更新 更多