任何尝试访问 MDX 组件中的道具都会导致构建失败,但开发工作正常
Any attempt to access props in MDX component results in failed build, but dev works just fine
我正在尝试获取从道具传递到渲染的任何内容。
如果未通过或不需要任何内容,则 MDX 渲染输出。如果props通过并尝试使用,则失败。
此站点上唯一剩下的就是让 MDX 在构建时实际呈现。
运行 [Gatsby Dev] works,并且 MDX 文件渲染可以使用传递给它的所有道具。任何 [Gatsby Build] 的尝试都失败了,说它不能读取未定义的内容。
我尝试将渲染包装在 MDX 提供程序中,在首先检查特定道具的条件语句中,但没有任何效果。 Gatsby Build 假装根本没有传递任何道具。
POST 模板
import React from 'react';
import { MDXRenderer } from "gatsby-plugin-mdx"
import {graphql, Link} from 'gatsby'
import { MDXProvider } from '@mdx-js/react';
import Layout from "../components2/Layout";
import Navbar from "../components2/Navbar"
**Styled components**
const Post = ({data}) => {
const { frontmatter} = data.mdx
onst result = data.mdx;
return (
<Layout>
<Navbar></Navbar>
<BlogLayout>
<Container>
<Banner>
<BannerInner>
<BannerSubtitle to={`/${frontmatter.tags[0]}`}>{frontmatter.tags[0]}
</BannerSubtitle>
<BannerTitle>{frontmatter.title}</BannerTitle>
<BannerByline><span>{frontmatter.date}</span></BannerByline>
</BannerInner>
</Banner>
</Container>
<GridWrap>
<MDXProvider>
<MDXRenderer props={result}>{result.body}</MDXRenderer>
</MDXProvider>
</GridWrap>
</BlogLayout>
</Layout>
);
}
export default Post
export const Pagequery = graphql`query PostBySlug($slug: String!) {
mdx(slug: {eq: $slug}, frontmatter: {templateKey: {eq: "blog-post"}}) {
frontmatter {
title
date(formatString: "MM/DD/YYYY")
tags
featuredimage {
childImageSharp {
gatsbyImageData(placeholder: DOMINANT_COLOR, layout: FULL_WIDTH)
}
}
}
body
excerpt
}
}
`
MARKDOWN 文件
---
templateKey: blog-post
title: Tables with style
date: 3122-03-08T01:54:06.882Z
description: "Nulla neque sem, gravida nec facilisis eu, interdum a neque. Morbi
in maximus dui. Morbi tincidunt ultrices nulla quis ullamcorper. Etiam egestas
id nisi in cursus. In in ex luctus, sodales sapien eu, semper ligula. Fusce
vitae turpis vel dui interdum eleifend nec nec eros. Praesent sed placerat
lacus. Aliquam lacinia arcu ut sollicitudin dictum. Aenean gravida commodo
velit, non accumsan tortor congue et. Duis malesuada nibh et odio finibus, a
fermentum lacus gravida. "
featuredpost: true
featuredimage: /img/44.jpg
tags:
- table
metaDescription: "Nulla neque sem, gravida nec facilisis eu, interdum a neque.
Morbi in maximus dui. Morbi tincidunt ultrices nulla quis ullamcorper. Etiam
egestas id nisi in cursus. In in ex luctus, sodales sapien eu, semper ligula.
Fusce vitae turpis vel dui interdum eleifend nec nec eros. Praesent sed
placerat lacus. Aliquam lacinia arcu ut sollicitudin dictum. Aenean gravida
commodo velit, non accumsan tortor congue et. Duis malesuada nibh et odio
finibus, a fermentum lacus gravida. "
---
import { getImage, GatsbyImage } from "gatsby-plugin-image";
## Post Body
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eleifend iaculis nunc ut posuere. Integer mollis interdum nisi eu pellentesque. Quisque euismod ipsum mi, in rutrum nisl malesuada quis. In hac habitasse platea dictumst. Nullam tempor iaculis varius.
## Local Images
<div className="image-grid">
{this.props.frontmatter.title}
</div>
GATSBY 配置
plugins: [
{
// keep as first gatsby-source-filesystem plugin for gatsby image support
resolve: "gatsby-source-filesystem",
options: {
path: `${__dirname}/static/img`,
name: "uploads",
},
},
{
resolve: "gatsby-source-filesystem",
options: {
path: `${__dirname}/src/pages/blog`,
name: "pages",
},
},
{
resolve: "gatsby-source-filesystem",
options: {
path: `${__dirname}/src/images`,
name: "images",
},
},
{
resolve: 'gatsby-plugin-local-search',
options: {
name: 'pages',
engine: 'flexsearch',
query:`
query {
allMdx(sort: { fields: [frontmatter___date], order: DESC }, filter: {frontmatter: {templateKey: {eq: "blog-post"}}}) {
nodes {
excerpt
slug
body
frontmatter {
date(formatString: "MMMM DD, YYYY")
title
tags
featuredimage {
publicURL
childImageSharp {
gatsbyImageData(placeholder: DOMINANT_COLOR, layout: FULL_WIDTH)
}
}
}
}
}
}
`,
ref: 'slug',
index: ['title', 'excerpt'],
store: ['title', 'excerpt', 'slug', 'tags', 'image'],
normalizer: ({ data }) =>
data.allMdx.nodes.map(node => ({
title: node.frontmatter.title,
excerpt: node.excerpt,
slug: node.slug,
tags: node.frontmatter.tags,
image: node.frontmatter.featuredimage.childImageSharp.gatsbyImageData
})),
}
},
`gatsby-plugin-react-helmet`,
"gatsby-plugin-image",
"gatsby-plugin-sharp",
"gatsby-transformer-sharp",
`gatsby-plugin-netlify`,
`gatsby-plugin-remove-fingerprints`,
`gatsby-plugin-styled-components`,
{
resolve: "gatsby-plugin-netlify-cms",
options: {
modulePath: `${__dirname}/src/cms/cms.js`,
},
},
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `Matt Site`,
short_name: `Another site`,
start_url: `/`,
background_color: `#6b37bf`,
theme_color: `#6b37bf`,
// Enables "Add to Homescreen" prompt and disables browser UI (including back button)
// see https://developers.google.com/web/fundamentals/web-app-manifest/#display
display: `standalone`,
icon: `src/images/icon.png`, // This path is relative to the root of the site.
},
},
{
resolve: `gatsby-plugin-mdx`,
options: {
extensions: [`.mdx`, `.md`],
gatsbyRemarkPlugins: [
{
resolve: "gatsby-remark-autolink-headers",
options:{
icon: false
}
},
{
resolve: "gatsby-remark-relative-images",
options: {
staticFolderName: 'static',
},
},
{
resolve: "gatsby-remark-images",
options: {
// It's important to specify the maxWidth (in pixels) of
// the content container as this plugin uses this as the
// base for generating different widths of each image.
maxWidth: 2048,
},
},
{
resolve: "gatsby-remark-copy-linked-files",
options: {
destinationDir: "static",
},
},
],
},
},
],
包裹JSON
"@babel/runtime": "^7.17.8",
"@fontsource/anton": "^4.5.2",
"@fontsource/epilogue": "^4.5.4",
"@mdx-js/mdx": "^1.6.22",
"@mdx-js/react": "^1.6.22",
"add": "^2.0.6",
"babel-plugin-styled-components": "^2.0.6",
"flexsearch": "^0.7.21",
"framer-motion": "^6.2.8",
"gatsby": "^4.1.2",
"gatsby-awesome-pagination": "^0.3.8",
"gatsby-image": "^3.11.0",
"gatsby-plugin-emotion": "^7.9.0",
"gatsby-plugin-image": "^2.1.0",
"gatsby-plugin-local-search": "^2.0.1",
"gatsby-plugin-manifest": "^4.8.1",
"gatsby-plugin-mdx": "^3.1.1",
"gatsby-plugin-netlify": "^4.1.0",
"gatsby-plugin-netlify-cms": "^6.8.0",
"gatsby-plugin-react-helmet": "^5.8.0",
"gatsby-plugin-remove-fingerprints": "^0.0.2",
"gatsby-plugin-sharp": "^4.10.0-next.3",
"gatsby-plugin-sitemap": "^5.8.0",
"gatsby-plugin-styled-components": "^5.9.0",
"gatsby-remark-autolink-headers": "^5.9.0",
"gatsby-remark-copy-linked-files": "^5.9.0",
"gatsby-remark-images": "^6.8.1",
"gatsby-remark-relative-images": "^2.0.2",
"gatsby-remark-table-of-contents": "^2.0.0",
"gatsby-source-filesystem": "^4.8.1",
"gatsby-transformer-remark": "^5.9.0",
"gatsby-transformer-sharp": "^4.10.0-next.2",
"hamburger-react": "^2.4.1",
"netlify-cms-app": "^2.15.66",
"netlify-cms-media-library-cloudinary": "^1.3.10",
"netlify-cms-media-library-uploadcare": "^0.5.10",
"react": "^17.0.1",
"react-collapsed": "^3.3.0",
"react-dom": "^17.0.1",
"react-helmet": "^6.1.0",
"react-use-flexsearch": "^0.1.1",
"remark-slug": "^7.0.1",
"styled-components": "^5.3.3",
"yarn": "^1.22.17"
尝试添加这一行:
const Post = ({data}) => {
if (!data) return null; //add this
const { frontmatter} = data.mdx
const result = data.mdx;
数据是 undefined
,直到您的 graphql 查询的响应返回,这需要一点时间。您可以在等待加载时放入加载屏幕或一些骨架块来渲染而不是 null
。
if (!data) return <LoadingScreen />;
其他一些对此有帮助的工具(在这种情况下您不需要)是:
可选链接
const result = data?.mdx
条件渲染
{ data &&
return (
<Layout>
...
}
编辑
如果你在尝试之后仍然苦苦挣扎,也许你应该,而不是破坏道具,控制台记录所有道具,
const Post = (props) => {
console.log(props)
检查传入的props的形状是否符合你的预期
如果同样失败,您可以尝试检查浏览器上的网络选项卡,看看您是否真的从 gql 接收数据。
我正在尝试获取从道具传递到渲染的任何内容。
如果未通过或不需要任何内容,则 MDX 渲染输出。如果props通过并尝试使用,则失败。
此站点上唯一剩下的就是让 MDX 在构建时实际呈现。
运行 [Gatsby Dev] works,并且 MDX 文件渲染可以使用传递给它的所有道具。任何 [Gatsby Build] 的尝试都失败了,说它不能读取未定义的内容。
我尝试将渲染包装在 MDX 提供程序中,在首先检查特定道具的条件语句中,但没有任何效果。 Gatsby Build 假装根本没有传递任何道具。
POST 模板
import React from 'react';
import { MDXRenderer } from "gatsby-plugin-mdx"
import {graphql, Link} from 'gatsby'
import { MDXProvider } from '@mdx-js/react';
import Layout from "../components2/Layout";
import Navbar from "../components2/Navbar"
**Styled components**
const Post = ({data}) => {
const { frontmatter} = data.mdx
onst result = data.mdx;
return (
<Layout>
<Navbar></Navbar>
<BlogLayout>
<Container>
<Banner>
<BannerInner>
<BannerSubtitle to={`/${frontmatter.tags[0]}`}>{frontmatter.tags[0]}
</BannerSubtitle>
<BannerTitle>{frontmatter.title}</BannerTitle>
<BannerByline><span>{frontmatter.date}</span></BannerByline>
</BannerInner>
</Banner>
</Container>
<GridWrap>
<MDXProvider>
<MDXRenderer props={result}>{result.body}</MDXRenderer>
</MDXProvider>
</GridWrap>
</BlogLayout>
</Layout>
);
}
export default Post
export const Pagequery = graphql`query PostBySlug($slug: String!) {
mdx(slug: {eq: $slug}, frontmatter: {templateKey: {eq: "blog-post"}}) {
frontmatter {
title
date(formatString: "MM/DD/YYYY")
tags
featuredimage {
childImageSharp {
gatsbyImageData(placeholder: DOMINANT_COLOR, layout: FULL_WIDTH)
}
}
}
body
excerpt
}
}
`
MARKDOWN 文件
---
templateKey: blog-post
title: Tables with style
date: 3122-03-08T01:54:06.882Z
description: "Nulla neque sem, gravida nec facilisis eu, interdum a neque. Morbi
in maximus dui. Morbi tincidunt ultrices nulla quis ullamcorper. Etiam egestas
id nisi in cursus. In in ex luctus, sodales sapien eu, semper ligula. Fusce
vitae turpis vel dui interdum eleifend nec nec eros. Praesent sed placerat
lacus. Aliquam lacinia arcu ut sollicitudin dictum. Aenean gravida commodo
velit, non accumsan tortor congue et. Duis malesuada nibh et odio finibus, a
fermentum lacus gravida. "
featuredpost: true
featuredimage: /img/44.jpg
tags:
- table
metaDescription: "Nulla neque sem, gravida nec facilisis eu, interdum a neque.
Morbi in maximus dui. Morbi tincidunt ultrices nulla quis ullamcorper. Etiam
egestas id nisi in cursus. In in ex luctus, sodales sapien eu, semper ligula.
Fusce vitae turpis vel dui interdum eleifend nec nec eros. Praesent sed
placerat lacus. Aliquam lacinia arcu ut sollicitudin dictum. Aenean gravida
commodo velit, non accumsan tortor congue et. Duis malesuada nibh et odio
finibus, a fermentum lacus gravida. "
---
import { getImage, GatsbyImage } from "gatsby-plugin-image";
## Post Body
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eleifend iaculis nunc ut posuere. Integer mollis interdum nisi eu pellentesque. Quisque euismod ipsum mi, in rutrum nisl malesuada quis. In hac habitasse platea dictumst. Nullam tempor iaculis varius.
## Local Images
<div className="image-grid">
{this.props.frontmatter.title}
</div>
GATSBY 配置
plugins: [
{
// keep as first gatsby-source-filesystem plugin for gatsby image support
resolve: "gatsby-source-filesystem",
options: {
path: `${__dirname}/static/img`,
name: "uploads",
},
},
{
resolve: "gatsby-source-filesystem",
options: {
path: `${__dirname}/src/pages/blog`,
name: "pages",
},
},
{
resolve: "gatsby-source-filesystem",
options: {
path: `${__dirname}/src/images`,
name: "images",
},
},
{
resolve: 'gatsby-plugin-local-search',
options: {
name: 'pages',
engine: 'flexsearch',
query:`
query {
allMdx(sort: { fields: [frontmatter___date], order: DESC }, filter: {frontmatter: {templateKey: {eq: "blog-post"}}}) {
nodes {
excerpt
slug
body
frontmatter {
date(formatString: "MMMM DD, YYYY")
title
tags
featuredimage {
publicURL
childImageSharp {
gatsbyImageData(placeholder: DOMINANT_COLOR, layout: FULL_WIDTH)
}
}
}
}
}
}
`,
ref: 'slug',
index: ['title', 'excerpt'],
store: ['title', 'excerpt', 'slug', 'tags', 'image'],
normalizer: ({ data }) =>
data.allMdx.nodes.map(node => ({
title: node.frontmatter.title,
excerpt: node.excerpt,
slug: node.slug,
tags: node.frontmatter.tags,
image: node.frontmatter.featuredimage.childImageSharp.gatsbyImageData
})),
}
},
`gatsby-plugin-react-helmet`,
"gatsby-plugin-image",
"gatsby-plugin-sharp",
"gatsby-transformer-sharp",
`gatsby-plugin-netlify`,
`gatsby-plugin-remove-fingerprints`,
`gatsby-plugin-styled-components`,
{
resolve: "gatsby-plugin-netlify-cms",
options: {
modulePath: `${__dirname}/src/cms/cms.js`,
},
},
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `Matt Site`,
short_name: `Another site`,
start_url: `/`,
background_color: `#6b37bf`,
theme_color: `#6b37bf`,
// Enables "Add to Homescreen" prompt and disables browser UI (including back button)
// see https://developers.google.com/web/fundamentals/web-app-manifest/#display
display: `standalone`,
icon: `src/images/icon.png`, // This path is relative to the root of the site.
},
},
{
resolve: `gatsby-plugin-mdx`,
options: {
extensions: [`.mdx`, `.md`],
gatsbyRemarkPlugins: [
{
resolve: "gatsby-remark-autolink-headers",
options:{
icon: false
}
},
{
resolve: "gatsby-remark-relative-images",
options: {
staticFolderName: 'static',
},
},
{
resolve: "gatsby-remark-images",
options: {
// It's important to specify the maxWidth (in pixels) of
// the content container as this plugin uses this as the
// base for generating different widths of each image.
maxWidth: 2048,
},
},
{
resolve: "gatsby-remark-copy-linked-files",
options: {
destinationDir: "static",
},
},
],
},
},
],
包裹JSON
"@babel/runtime": "^7.17.8",
"@fontsource/anton": "^4.5.2",
"@fontsource/epilogue": "^4.5.4",
"@mdx-js/mdx": "^1.6.22",
"@mdx-js/react": "^1.6.22",
"add": "^2.0.6",
"babel-plugin-styled-components": "^2.0.6",
"flexsearch": "^0.7.21",
"framer-motion": "^6.2.8",
"gatsby": "^4.1.2",
"gatsby-awesome-pagination": "^0.3.8",
"gatsby-image": "^3.11.0",
"gatsby-plugin-emotion": "^7.9.0",
"gatsby-plugin-image": "^2.1.0",
"gatsby-plugin-local-search": "^2.0.1",
"gatsby-plugin-manifest": "^4.8.1",
"gatsby-plugin-mdx": "^3.1.1",
"gatsby-plugin-netlify": "^4.1.0",
"gatsby-plugin-netlify-cms": "^6.8.0",
"gatsby-plugin-react-helmet": "^5.8.0",
"gatsby-plugin-remove-fingerprints": "^0.0.2",
"gatsby-plugin-sharp": "^4.10.0-next.3",
"gatsby-plugin-sitemap": "^5.8.0",
"gatsby-plugin-styled-components": "^5.9.0",
"gatsby-remark-autolink-headers": "^5.9.0",
"gatsby-remark-copy-linked-files": "^5.9.0",
"gatsby-remark-images": "^6.8.1",
"gatsby-remark-relative-images": "^2.0.2",
"gatsby-remark-table-of-contents": "^2.0.0",
"gatsby-source-filesystem": "^4.8.1",
"gatsby-transformer-remark": "^5.9.0",
"gatsby-transformer-sharp": "^4.10.0-next.2",
"hamburger-react": "^2.4.1",
"netlify-cms-app": "^2.15.66",
"netlify-cms-media-library-cloudinary": "^1.3.10",
"netlify-cms-media-library-uploadcare": "^0.5.10",
"react": "^17.0.1",
"react-collapsed": "^3.3.0",
"react-dom": "^17.0.1",
"react-helmet": "^6.1.0",
"react-use-flexsearch": "^0.1.1",
"remark-slug": "^7.0.1",
"styled-components": "^5.3.3",
"yarn": "^1.22.17"
尝试添加这一行:
const Post = ({data}) => {
if (!data) return null; //add this
const { frontmatter} = data.mdx
const result = data.mdx;
数据是 undefined
,直到您的 graphql 查询的响应返回,这需要一点时间。您可以在等待加载时放入加载屏幕或一些骨架块来渲染而不是 null
。
if (!data) return <LoadingScreen />;
其他一些对此有帮助的工具(在这种情况下您不需要)是:
可选链接
const result = data?.mdx
条件渲染
{ data &&
return (
<Layout>
...
}
编辑
如果你在尝试之后仍然苦苦挣扎,也许你应该,而不是破坏道具,控制台记录所有道具,
const Post = (props) => {
console.log(props)
检查传入的props的形状是否符合你的预期
如果同样失败,您可以尝试检查浏览器上的网络选项卡,看看您是否真的从 gql 接收数据。