Я пытаюсь получить одну строку чего-либо из переданного реквизита для рендеринга.
Если ничего не передается или не требуется, выполняется рендеринг MDX. Если реквизит передается и пытается быть использован, сбой.
Единственное, что осталось на этом сайте, — заставить MDX фактически отображаться при сборке.
Запуск [Gatsby Dev] работает, и рендеринг файла MDX может использовать все переданные ему реквизиты. Любая попытка [Gatsby Build], и она не может сказать, что не может читать undefined.
Я попытался обернуть рендеринг в поставщике MDX, в условном выражении, которое сначала проверяет определенные реквизиты, но ничего не работает. Gatsby Build делает вид, что реквизит вообще не передается.
ШАБЛОН СООБЩЕНИЯ
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
}
}
`
ФАЙЛ УКАЗАНИЯ
---
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>
КОНФИГУРАЦИЯ ГЭТСБИ
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;
data будет undefined, пока не вернется ответ на ваш запрос graphql, что занимает некоторое время. Вы можете добавить экран загрузки или несколько скелетных блоков для рендеринга вместо null, пока ждете загрузки.
if (!data) return <LoadingScreen />;
некоторые другие инструменты, которые помогают в этом (которые вам не нужны в этом случае):
const result = data?.mdx
{ data &&
return (
<Layout>
...
}
Если вы все еще боретесь после того, как попробовали это, возможно, вам следует вместо уничтожения реквизита записывать в консоль все реквизиты,
const Post = (props) => {
console.info(props)
чтобы проверить, является ли форма переданных реквизитов такой, как вы ожидаете.
Если и это не помогло, вы можете попробовать проверить вкладку сети в своем браузере и выяснить, действительно ли вы получаете данные от gql.
Нет, я просто рад, что могу помочь :) поздравляю с работой. Вы можете дать мой ответ плюс, хотя;)
Решение
if (!data) return null;Сработало отлично! Оказалось, что мои предыдущие попытки использовать условный рендеринг не работали, потому что в mdx я пытался использовать{props.frontmatter.title}вместо{props.props.frontmatter.titleформы, которую я создал. Большое спасибо! Могу ли я как-нибудь угостить вас кофе или поблагодарить вас другим способом?