Javascript 来自Gatsby GraphQL的数据总是返回未定义?
盖茨比·诺布在这里,所以请容忍我。我有一个组件,它接受index.js中的道具,应该从一组对象接收数据,但总是会收到错误Javascript 来自Gatsby GraphQL的数据总是返回未定义?,javascript,reactjs,graphql,gatsby,Javascript,Reactjs,Graphql,Gatsby,盖茨比·诺布在这里,所以请容忍我。我有一个组件,它接受index.js中的道具,应该从一组对象接收数据,但总是会收到错误TypeError:cannotread属性“map”of undefined,它指的是Hero.js component index.js调用的属性 我的假设是,index.js中查询的数据要么不够具体,要么在接收数据之前呈现组件。以下是index.js文件: import { graphql } from 'gatsby'; import { Layout, SEO, H
TypeError:cannotread属性“map”of undefined
,它指的是Hero.js component index.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;
从“盖茨比”导入{graphql};
从“组件”导入{Layout,SEO,Hero};
常量IndexPage=({data})=>{
const dataFetch=data.contentfulTemplateIndex.heromes;
让测试仪=()=>{
for(让count=0;count
以下是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;
import{Link}来自“盖茨比”;
从“@contentful/richtextreact呈现程序”导入{documentoreactcomponents};
从“类名称”导入cx;
从“/hero.module.scss”导入样式;
康斯特英雄=(道具)=>{
返回(
{props.primaryLabel}
{props.labels.map((label)=>{
返回{label};
})}
{props.impactText}
);
};
导出默认英雄;
局外人不可能在没有软件的情况下调试您的代码
调试GraphQL的最佳方法是使用浏览器的GraphiQL界面
gatsby develope
。如果由于类型错误而失败,请删除导致类型错误的代码行(但不是GraphQL查询的代码!)。您需要让您的开发服务器运行http://localhost:8000/___graphql
console.log(props)
,以便您可以检查数据对象:
const英雄=(道具)=>{
控制台日志(道具);
返回(
局外人不可能在没有软件的情况下调试您的代码
调试GraphQL的最佳方法是使用浏览器的GraphiQL界面
gatsby develope
。如果由于TypeError
而失败,请删除导致类型错误的代码行(但不是GraphQL查询的代码!)。您需要运行开发服务器http://localhost:8000/___graphql
console.log(props)
,以便您可以检查数据对象:
const英雄=(道具)=>{
控制台日志(道具);
返回(
这通常意味着您的一些数据没有要映射的标签。您可以在GraphiQL中运行查询以确保。如果您想渲染英雄组件,即使是没有标签的图像,也可以简单地添加条件:props.labels&&props.labels.map()
这通常意味着您的一些数据没有要映射的标签。您可以在GraphiQL中运行查询以确保。如果您想渲染英雄组件,即使是没有标签的图像,也可以添加条件:props.labels&&props.labels.map()