[英]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 界面。
運行gatsby develop
。 如果由於TypeError
而失敗,請刪除導致類型錯誤的代碼行(但不是您的 GraphQL 查詢的代碼。)。 您需要讓您的開發服務器運行。
打開瀏覽器,使用 URL: http://localhost:8000/___graphql
從代碼中復制 graphQL 查詢並將其粘貼到 GraphiQL 查詢 window 中。
您可以在那里訪問您的數據嗎? 如果不是,您在編寫查詢時出錯,或者數據不在應有的位置。
這樣您就可以確保數據存在。
它還有助於console.log(props)
以便您可以檢查數據 object:
const Hero = (props) => {
console.log(props);
return (
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.