簡體   English   中英

無法讀取未定義的屬性“地圖”(ReactJS-Apollo-Graphql)

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

我正在嘗試使用 React JS 創建一個虛擬項目,並且我從 SpaceX Graphql API 獲取我的數據。 我有兩個組件(主頁、詳細信息),並且這兩個組件都應該從 API 獲取數據。 但是,我查詢在 Home 組件中有效,但在 Details 組件中無效。 我使用了完全相同的方法,但似乎不起作用。 請幫我解決這個問題。

如果需要,您可以在https://github.com/affiqzaini/react-apollo-spacex 上嘗試整個過程。

這是我的 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;

這是我的詳細信息組件不起作用:

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;

這是我得到的錯誤:錯誤圖像

更新:我發現我在兩個查詢中得到了不同類型的數據。 在 Home(有效)中,我得到了一組數據。 在我的詳細信息組件中,我得到了一個對象。 這就是我不能使用地圖功能的原因嗎?

根據查詢文檔https://www.apollographql.com/docs/react/v2.5/essentials/queries/在此之后您不需要使用“else”:

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

而且你不會在你的 Home 組件中這樣做。 嘗試在“詳細信息”組件中也刪除“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>

如果要映射的返回數據仍為對象形式,則需要將對象轉換為數組。

Object.values(data.detailsData)獲取包含值的數組,或Object.entries(data.detailsData)獲取鍵值對的數組,即[[key1, value1], [key2, value2], ...[keyN, valueN]]

對象值

Object.values()方法返回給定對象自己的可枚舉屬性值的數組,其順序與for...in循環提供的順序相同。

Object.entries()

Object.entries()方法返回給定對象自己的可枚舉字符串鍵控屬性[key, value]對的數組,其順序與for...in循環提供的順序相同。

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

我發現我得到的數據是對象形式而不是數組。 要訪問該對象,您可以使用上面 DrewReese 的方法或我發現更簡單的這種方式:

*** '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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM