Невозможно получить свойство "allShopifyProduct" из данных, которые я получаю из graphQL - PullRequest
0 голосов
/ 06 июля 2019

Я изучал, как использовать плагин shopify, но для этой страницы он не может получить доступ к данным из моего shopify.

Для других страниц я использую подобный код, и он отлично работает только для этой страницы. Я не могу понять ошибку> <</p>

Какие ошибки я допустил?

Это мой запрос к графику

{
  "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>

        </>
      )


  }

}```

1 Ответ

0 голосов
/ 06 июля 2019

Вместо componentDidMount вы должны проверить componentDidUpdate как,

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);
};
...