【问题标题】:Gatsby: Index page "/" fails to load when using MDX, other path loadsGatsby:使用MDX时索引页“/”加载失败,其他路径加载
【发布时间】:2019-12-30 13:05:52
【问题描述】:

我正在使用 Gatsby 创建一个文档站点,使用 .mdx 来管理内容。我已经配置了gatsby-node.js 并创建了模板。一切路径都可以正常工作,但是,索引页面无法从 GraphQL 查询中获取结果。我已经清除了缓存并分别重建了项目。我尝试修复Github,建议将index.js 重命名为main.js。这在 dev 上无缝运行,但在 prod 中却不行。

这是gatsby-node.js 文件:

const {createFilePath} = require(`gatsby-source-filesystem`)
const path = require(`path`)

exports.createPages = ({actions, graphql}) => {
    const {createPage} = actions
    const blogPostTemplate = path.resolve('src/templates/postTemplate.js')

    return(graphql(`
    {
        allMdx {
          nodes {
            frontmatter {
              title
            }
            fields {
              slug
            }
          }
        }
    } 
    `)).then(result => {
        if(result.errors) {
            throw result.errors
        }

        const posts = result.data.allMdx.nodes

        posts.forEach(post => {
            createPage({
                path: post.fields.slug,
                component: blogPostTemplate,
                context: {
                    slug: post.fields.slug
                }
            })
        })
    })
}

exports.onCreateNode = ({node, actions, getNode}) => {
    const { createNodeField } = actions
    if(node.internal.type === `Mdx`) {
        const value = createFilePath({node, getNode})
        createNodeField({
            name: `slug`,
            node,
            value
        })
    }
}

这是postTemplate.js 文件:

import React from 'react'
import {graphql} from 'gatsby'
import {MDXRenderer} from 'gatsby-plugin-mdx'

import Layout from '../components/Layout/Layout';

export default ({data}) => {
  const {body, tableOfContents, fields} = data.mdx
  return (
    <Layout>
      {tableOfContents}
      <MDXRenderer>
        {body}
      </MDXRenderer>
      {fields}
    </Layout>
    
  )
}

export const query  = graphql`
query PostBySlug($slug: String!) {
  mdx (fields: {slug: {eq: $slug}}) {
    body
    tableOfContents
    fields {
      slug
    }
  }
}
`

任何建议都将受到高度赞赏。

【问题讨论】:

  • 为什么您将slug 作为上下文变量传递给模板而不是id
  • 我正在使用slug 来构建页内标题导航。

标签: javascript reactjs gatsby


【解决方案1】:

我找到了解决问题的方法。我发现索引(/)页面没有使用postTemplate.js。所以我的解决方法是将postTemplate.js文件的内容复制到index.js文件中。然后我修改了graphql 查询以仅获取/ 内容。我不知道这是否是最好的解决方案,但现在可以正常工作了。

【讨论】:

    【解决方案2】:

    为您的createPage 路径使用三元运算符。我假设您的索引的 slug 名称是“索引”。

    path: post.fields.slug === 'index' ? '/' : `/${post.fields.slug}`
    

    【讨论】:

      猜你喜欢
      • 2021-10-24
      • 2015-06-15
      • 1970-01-01
      • 2018-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多