繁体   English   中英

来自 Gatsby GraphQL 的数据总是返回未定义?

[英]Data from Gatsby GraphQL always returns undefined?

盖茨比菜鸟在这里,所以请多多包涵。 我有一个组件,它接受来自 index.js 的道具,它应该从对象数组接收数据,但总是会收到错误TypeError: Cannot read property 'map' of undefined where it引用 Hero.js 组件索引.js 正在呼吁。

我的假设是 index.js 中查询的数据要么不够具体,要么是在接收到数据之前渲染组件。 这是 index.js 文件:

import { graphql } from 'gatsby';

import { Layout, SEO, Hero } from 'components';

const IndexPage = ({ data }) => {
  const dataFetch = data.contentfulTemplateIndex.heroes;
  let tester = () => {
    for (let count = 0; count < dataFetch.length; count++) {
      return <Hero {...props} />;
    }
  };
  console.log(dataFetch);
  let props = {
    impactText: dataFetch.impactText,
    labels: dataFetch.labels,
    primaryLabel: dataFetch.primaryLabel,
    location: dataFetch.location
    // supportingText: dataFetch.supportingText.json
  };

  return (
    <Layout>
      {dataFetch && tester()}
    </Layout>
  );
};

export const query = graphql`
  query {
    contentfulTemplateIndex {
      heroes {
        image {
          fluid {
            src
          }
        }
        impactText
        labels
        location
        primaryLabel
        supportingText {
          json
        }
      }
    }
  }
`;

export default IndexPage;

这是 index.js 正在调用的 Hero.js 组件:

import { Link } from 'gatsby';
import { documentToReactComponents } from '@contentful/rich-text-react-renderer';
import cx from 'classnames';

import styles from './hero.module.scss';

const Hero = (props) => {
  return (
    <div>
      <ul>
        <Link className={styles.pills}>{props.primaryLabel}</Link>
        {props.labels.map((label) => {
          return <Link className={styles.pills}>{label}</Link>;
        })}
      </ul>
      <div className={styles.grid}>
        <h1>{props.impactText}</h1>
      </div>
    </div>
  );

};

export default Hero;

如果没有最低限度的可重现示例,局外人就不可能调试您的代码。

调试 GraphQL 的最佳方法是使用浏览器的 Graph i QL 界面。

  1. 运行gatsby develop 如果由于TypeError而失败,请删除导致类型错误的代码行(但不是您的 GraphQL 查询的代码。)。 您需要让您的开发服务器运行。

  2. 打开浏览器,使用 URL: http://localhost:8000/___graphql

  3. 从代码中复制 graphQL 查询并将其粘贴到 GraphiQL 查询 window 中。

  4. 您可以在那里访问您的数据吗? 如果不是,您在编写查询时出错,或者数据不在应有的位置。

这样您就可以确保数据存在。

它还有助于console.log(props)以便您可以检查数据 object:

const Hero = (props) => {
  console.log(props);
  return (

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM