【问题标题】:Unable to get property "allShopifyProduct" from the data I get from graphQL无法从我从 graphQL 获得的数据中获取属性“allShopifyProduct”
【发布时间】:2019-07-06 02:40:29
【问题描述】:

我正在学习如何使用 shopify 插件,但对于此页面,它无法访问我的 shopify 中的数据。

对于其他页面,我使用了类似的代码,它仅适用于该页面我无法确定错误>

我犯了什么错误?

这是我的 graphql 查询

{
  "data": {
    "allShopifyProduct": {
      "nodes": [
        {
          "id": "Shopify__Product__Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0LzIyMDEzNzg2MTk0NDY=",
          "images": [
            {
              "id": "Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0SW1hZ2UvNzU5MDg5NDAxMDQyMg==",
              "originalSrc": "https://cdn.shopify.com/s/files/1/0164/9121/6950/products/Forfacebooksquare.jpg?v=1562306206"
            }
          ],
          "title": "NJ Experience",
          "description": "An Owlnext-Intern",
          "handle": "nj-experience"
        }
      ]
    }
  }
}

这是我的代码

import React, {Component} from 'react';
import { withStyles } from '@material-ui/styles';
//import Grid from '@material-ui/core/Grid';
import Card from '@material-ui/core/Card';
import CardActionArea from '@material-ui/core/CardActionArea';
//import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
//import {BrowserRouter,Route,Link} from 'react-router-dom';
//import ProductListing from "../ProductListing";
import datas, {Bought} from '../components/data';
import { Link , navigate} from "gatsby";
import { useStaticQuery, graphql } from 'gatsby';


const styles = {
    card : {
        height : 350
    }
}


class Cards extends Component{

    constructor(props){
        super(props);
        this.state = {

        };
    };


    // Another method which I tried but not working right now too so i remain the code here

    // data = useStaticQuery(
    //     graphql`
    //     query {
    //         allShopifyProduct {
    //           nodes {
    //             id
    //             images {
    //               id
    //               originalSrc
    //             }
    //             title
    //             description
    //             handle
    //           }
    //         }
    //       }
    //     ` 
    //   );


    handleSomething= () =>{
        console.log('test')
        this.analyticsEvents();
        this.handlePushData();
    };

    analyticsEvents = () =>{
        console.log("ga");

       // ga('send', 'event' ,'Bought1', 'Bought2', 'Bought3');

    };

    //Checking
    componentDidMount(){
        console.log(this.props.data.allShopifyProduct.nodes[0].handle);
      };


    handlePushData = () => {
        navigate(`/product/${this.props.data.allShopifyProduct.nodes[0].handle}/`);
        Bought.push({ImageLink: this.props.ImageLink, Title: this.props.Title , Price: this.props.Price});
    };

    render(){

        const { classes } = this.props;

        return(

            <Card className={classes.card}>
                <CardActionArea>

                    <CardMedia
                        style = {{objectFit: "contain"}}
                        component="img"
                        height="200"
                        image= {this.props.ImageLink}
                        /> 

                    <CardContent>

                    <Typography gutterBottom  component="h2"> 
                        {this.props.Title}
                    </Typography>

                    <Typography variant="body2" color="textSecondary" component="p">
                    {this.props.Price}
                    </Typography>

                    <Button size="small" variant="contained" style = {{marginTop: 10, backgroundColor: "#0ABAB5"}} 
                    onClick={this.handleSomething}>
                        ADD TO CART
                    </Button>

                </CardContent>

                </CardActionArea>
            </Card>


        )
    }
}


export const query = graphql`
query Query{
    allShopifyProduct {
      nodes {
        id
        images {
          id
          originalSrc
        }
        title
        description
        handle
      }
    }
  }
` 

export default withStyles(styles)(Cards);

应该可以获取数据

更新

这是我的 index.js,其中包含 Card 组件


Thanks so much for helping out! This is the first page which include the cards component

Btw,do you mean that the data in graphQl have to pass in to the Cards component in this page? I thought the graphQL data could be import at any .js file as long as you call it in the .js file you want

import React, {Component} from 'react';
import { Link } from "gatsby"
import Layout from "../components/layout"
import Image from "../components/image"
import SEO from "../components/seo"
import Cards from '../components/Cards';
import Grid from '@material-ui/core/Grid';
//Assets
import datas from '../components/data';
import { graphql } from "gatsby"



export default class HomePage extends Component{


  render(){

      return(
        <>
          <SEO title="Home" />
          <Grid
              container
              spacing={8}
          >
              {datas.map(books =>(
                  <Grid key={books.Title} item xs={3}>    

                      <Cards history={this.props.history}  ImageLink={books.ImageLink} Title={books.Title} Price={books.Price} />
                  </Grid>
              ))}            
          </Grid>

        </>
      )


  }

}```

【问题讨论】:

  • console.logcomponentDidMount 函数中打印什么?
  • 它不打印任何东西,直接显示此错误 TypeError: Unable to get property 'allShopifyProduct' of undefined or null reference

标签: javascript reactjs graphql shopify gatsby


【解决方案1】:

你应该签入componentDidUpdate,而不是componentDidMount

componentDidUpdate(){
   console.log(this.props.data.allShopifyProduct.nodes[0].handle);
};

由于componentDidMount 仅在组件挂载时执行,并且您的数据可能需要一段时间才能到达,因此componentDidMount 可能会在数据到达this.props.data 之前执行。最好的方法是在componentDidUpdate 函数中。

更新

当您像这样使用Cards 组件时,

<Cards history={this.props.history}  ImageLink={books.ImageLink} Title={books.Title} Price={books.Price} />

您将history 作为道具传递,而不是data,因此您必须使用它,

componentDidUpdate(){
   console.log(this.props.history.allShopifyProduct.nodes[0].handle);
};

【讨论】:

  • 在我应用您的建议后,这是同样的错误,代码中是否有任何错误导致它无法获取数据? TypeError:无法获取未定义或空引用的属性“allShopifyProduct”
  • handlePushData = () => { > 77 |导航(/product/${this.props.data.allShopifyProduct.nodes[0].handle}/); 78 |买了.push({ImageLink: this.props.ImageLink, Title: this.props.Title , Price: this.props.Price}); 79 | }; 这是第 77 行的错误消息
  • 将您的组件发布到您要添加Cards 组件的位置。
  • 您很可能错过了将数据作为道具传递给Cards 组件。或者this.props.data 为空。
  • 是因为我用this.props.history所以我需要传下去吗?
猜你喜欢
  • 2020-06-24
  • 1970-01-01
  • 1970-01-01
  • 2019-02-06
  • 2021-09-18
  • 2020-05-30
  • 2019-11-11
  • 2022-01-02
  • 1970-01-01
相关资源
最近更新 更多