简体   繁体   English

无法读取未定义的属性“地图”(ReactJS-Apollo-Graphql)

[英]Cannot read property 'map' of undefined (ReactJS-Apollo-Graphql)

I am trying to create a dummy project with React JS and Im getting my data from SpaceX Graphql API.我正在尝试使用 React JS 创建一个虚拟项目,并且我从 SpaceX Graphql API 获取我的数据。 I have two components (Home, Details) and both components are supposed to grab data from the API.我有两个组件(主页、详细信息),并且这两个组件都应该从 API 获取数据。 However, I query works in the Home component but it does not in the Details component.但是,我查询在 Home 组件中有效,但在 Details 组件中无效。 I used the exact same method and it doesn't seem to work.我使用了完全相同的方法,但似乎不起作用。 Do help me with this.请帮我解决这个问题。

You can try the whole thing at https://github.com/affiqzaini/react-apollo-spacex if you want.如果需要,您可以在https://github.com/affiqzaini/react-apollo-spacex 上尝试整个过程。

Here's my Home component which works:这是我的 Home 组件,它可以工作:

import React from 'react';
import { Query } from 'react-apollo';
import gql from 'graphql-tag';
import { BrowserRouter, NavLink } from 'react-router-dom';
import Route from 'react-router-dom/Route';
import 'react-bulma-components/dist/react-bulma-components.min.css';
import './App.css';
import Details from './Details';

const POSTS_QUERY = gql`
  {
    rockets {
      name
      country
      id
    }
  }
`;

function Home() {
  return (
    <BrowserRouter>
      <Route
        path='/'
        exact
        strict
        render={() => {
          return (
            <div
              className='tile is-ancestor'
              style={{
                justifyContent: 'space-evenly',
                alignItems: 'center',
                margin: 25
              }}
            >
              <Query query={POSTS_QUERY}>
                {({ loading, data }) => {
                  if (loading) return <p className='Loading'>Loading...</p>;
                  const { rockets } = data;
                  return rockets.map(post => (
                    <NavLink to={{ pathname: `/${post.id}` }}>
                      <div class='tile is-parent'>
                        <article
                          class='tile is-child box'
                          key={post.id}
                          style={{
                            backgroundColor: 'whitesmoke',
                            borderRadius: 10,
                            height: 400,
                            width: 300
                          }}
                        >
                          <figure
                            class='image container is-1by1'
                            style={{ marginBottom: 15 }}
                          >
                            <img
                              src={require(`./Images/${post.id.toString()}.jpg`)}
                              className='Rocket-Img'
                              alt='Rocket'
                            />
                          </figure>
                          <h2>{post.name}</h2>
                          <h4>{post.country}</h4>
                        </article>
                      </div>
                    </NavLink>
                  ));
                }}
              </Query>
            </div>
          );
        }}
      />
      <Route path='/:id' exact strict component={Details} />
    </BrowserRouter>
  );
}

export default Home;

Here's my Details component which does not work:这是我的详细信息组件不起作用:

import React from 'react';
import { useParams } from 'react-router';
import { Query, ApolloProvider } from 'react-apollo';
import gql from 'graphql-tag';
import ApolloClient from 'apollo-boost';
import './App.css';

function Details() {
  const rocketId = useParams();
  const QUERY_ROCKET = gql`
    {
      rocket(id: "${rocketId}") {
        id
        active
        boosters
        company
        cost_per_launch
        name
        stages
        success_rate_pct
        type
        wikipedia
        first_flight
        country
        description
      }
    }
  `;

  return (
    <Query query={QUERY_ROCKET}>
      {({ loading, data }) => {
        if (loading) {
          return <p className='Loading'>Loading...</p>;
        } else {
          const { detailsData } = data;
          return detailsData.map(post => (
            <div>
              <p>{post.id}</p>
            </div>
          ));
        }
      }}
    </Query>
  );
}
export default Details;

Here's the error I get: Error Image这是我得到的错误:错误图像

Update: I found out that I get different type of data in the two queries.更新:我发现我在两个查询中得到了不同类型的数据。 In Home (which works), I get an array of data.在 Home(有效)中,我得到了一组数据。 In my details component, I get an object.在我的详细信息组件中,我得到了一个对象。 Is that why I cant use the map function?这就是我不能使用地图功能的原因吗?

According to Query docs https://www.apollographql.com/docs/react/v2.5/essentials/queries/ you don't need to use "else" after this:根据查询文档https://www.apollographql.com/docs/react/v2.5/essentials/queries/在此之后您不需要使用“else”:

if (loading) return <p className='Loading'>Loading...</p>;

And you don't do that in your Home component which works.而且你不会在你的 Home 组件中这样做。 Try to remove "else" as well in your Details component:尝试在“详细信息”组件中也删除“else”:

<Query query={QUERY_ROCKET}>
  {({ loading, data }) => {
    if (loading) return <p className='Loading'>Loading...</p>;
    const { detailsData } = data;
    return detailsData.map(post => (
      <div>
        <p>{post.id}</p>
      </div>
    ));
  }}
</Query>

If the returned data you want to map is still in object form then you need to convert the object to an array.如果要映射的返回数据仍为对象形式,则需要将对象转换为数组。

Object.values(data.detailsData) to get an array of just the values, or Object.entries(data.detailsData) to get an array of the key-value pairs, ie [[key1, value1], [key2, value2], ...[keyN, valueN]] . Object.values(data.detailsData)获取包含值的数组,或Object.entries(data.detailsData)获取键值对的数组,即[[key1, value1], [key2, value2], ...[keyN, valueN]]

Object.values 对象值

The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop. Object.values()方法返回给定对象自己的可枚举属性值的数组,其顺序与for...in循环提供的顺序相同。

Object.entries() Object.entries()

The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop. Object.entries()方法返回给定对象自己的可枚举字符串键控属性[key, value]对的数组,其顺序与for...in循环提供的顺序相同。

return Object.values(detailsData).map(post => (
  <div>
    <p>{post.id}</p>
  </div>
));

I found out that the data that I'm getting is in an object form instead of an array.我发现我得到的数据是对象形式而不是数组。 To access the object, you can either use DrewReese's method above or the this way which I find to be simpler:要访问该对象,您可以使用上面 DrewReese 的方法或我发现更简单的这种方式:

*** 'rocket' is the name of my object *** 'rocket' 是我的对象的名称

return (
    <Query query={QUERY_ROCKET}>
      {({ loading, error, data }) => {
        if (loading) return <p className='Loading'>Loading...</p>;
        if (error) return `Error! ${error.message}`;

        const detailsData = data.rocket;
        return (
          <div>
            <p>{detailsData.id}</p>
            <p>{detailsData.name}</p>
            <p>{detailsData.company}</p>
            <p>{detailsData.stages}</p>
            <p>{detailsData.boosters}</p>
            <p>{detailsData.cost_per_launch}</p>
          </div>
        );
      }}
    </Query>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ReactJS/Javascript/Graphql/React-apollo:无法读取未定义的属性“加载” - ReactJS/Javascript/Graphql/React-apollo: Cannot read property 'loading' of undefined ReactJS/Javascript/Graphql/React-apollo:无法读取未定义的属性“名称” - ReactJS/Javascript/Graphql/React-apollo: Cannot read property 'name' of undefined Apollo GraphQL - 类型错误:无法读取未定义的属性“findOrCreateUser” - Apollo GraphQL - TypeError: Cannot read property 'findOrCreateUser' of undefined 无法读取未定义的属性“地图”-ReactJs - Cannot read property 'map' of undefined - ReactJs 类型错误:无法读取未定义的属性“地图”| ReactJS - TypeError: Cannot read property 'map' of undefined | ReactJS ReactJS:TypeError:无法读取未定义的属性“map” - ReactJS: TypeError: Cannot read property 'map' of undefined TypeError:无法读取 reactJS 上未定义的属性“映射” - TypeError: Cannot read property 'map' of undefined on reactJS Reactjs:类型错误:无法读取未定义的属性“地图” - Reactjs : TypeError: Cannot read property 'map' of undefined ReactJS TypeError:无法读取未定义的属性“ map” - ReactJS TypeError: Cannot read property 'map' of undefined 带有axios的reactjs“无法读取未定义的属性&#39;map&#39;” - reactjs with axios “Cannot read property 'map' of undefined`”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM