Graphql / Gatsby |变量“ $ slug”的无效值未定义;

时间:2019-12-10 15:49:32

标签: javascript graphql gatsby

当我尝试使用gatsby“创建页面”时出错

成功构建模式-1.092秒 成功createPages-0.044s 成功createPagesStatefully-0.173s 成功于PreExtractQueries-0.010s 成功更新架构-0.032秒

期望的非空类型String!不为空。 Console screenshot

控制台输出:

The GraphQL query from C:/Users/tonyk/Desktop/alterr/src/templates/serviceItem.js failed.

Errors:
  Variable "$slug" got invalid value undefined; Expected non-nullable type String! not to be null.

  GraphQL request:1:20
  1 | query ServiceQuery($slug: String!) {
    |                    ^
  2 |   dataJson(services: {elemMatch: {slug: {eq: $slug}}}) {
URL path:
  /services/undefined/
Context:
  {}

gatsby-node.js 创建页面

exports.createPages = async ({ actions: { createPage }, graphql }) => {
    const results = await graphql(`
    query {
        allDataJson {
          edges {
            node {
              services {
                slug
              }
            }
          }
        }
      }
    `);

    if(results.error) {
        console.error("Wrong!");
        return
    }

    results.data.allDataJson.edges.forEach(edge => {
        const item = edge.node.services;

        createPage({
            path: `/services/${item.slug}/`,
            component: require.resolve('./src/templates/serviceItem.js'),
            context: {
                slug: item.slug,
            }
        });
    });
}

serviceItem.js 页面模板

import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout"

export const query = graphql `
    query ServiceQuery($slug: String!) {
        dataJson(services: {elemMatch: {slug: {eq: $slug} }}) {
            services {
                id
                slug
                title
            }
        }
    }
`;

export default ({ data }) => {

    const item = data.dataJson.services;

    return (
        <Layout>
        <div>
        <h1>Hello
            {item.title}
        </h1>
        </div>
        </Layout>
    )
}

data.json(示例) 数据

{ 
    "services" : [
        { 
            "id": 1,
            "slug": "slug-slug",
            "icon": "someimg",
            "title": "title",
            "text": "some text 1"
        },
        { 
            "id": 2,
            "slug": "slug-slug-slug",
            "icon": "someicon",
            "title": "title",
            "text": "some text 2"
        }
    ]
}

0 个答案:

没有答案