首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >任何在MDX组件中访问道具的尝试都会导致生成失败,但是dev工作得很好。

任何在MDX组件中访问道具的尝试都会导致生成失败,但是dev工作得很好。
EN

Stack Overflow用户
提问于 2022-03-21 10:20:23
回答 1查看 686关注 0票数 0

我正试着得到从道具到渲染的任何东西的一行。

如果没有任何传递或需要,则MDX呈现出。如果道具通过并尝试使用,则失败。

这个站点上唯一剩下的东西就是让MDX在构建时实际呈现。

运行Gatsby可以工作,MDX文件呈现可以使用传递给它的所有道具。任何尝试Gatsby构建,它都失败了,说它不能读取未定义的。

我尝试过在MDX提供程序中包装呈现,使用的条件语句首先检查特定的道具,但是没有任何效果。盖茨比的构建假装根本没有道具被传递。

后模板

代码语言:javascript
复制
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
  }
}
`

标记文件

代码语言:javascript
复制
---
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配置

代码语言:javascript
复制
  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

代码语言:javascript
复制
    "@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"
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-22 09:58:51

尝试添加以下一行:

代码语言:javascript
复制
const Post = ({data}) => {
    if (!data) return null; //add this

    const { frontmatter} = data.mdx
    const result = data.mdx;

数据是undefined,直到您的graphql查询的响应返回,这需要一些时间。在等待加载时,您可以放入加载屏幕或一些骨架块来呈现,而不是null

代码语言:javascript
复制
if (!data) return <LoadingScreen />;

在这种情况下(在本例中您不需要),其他一些工具可以帮助解决这个问题:

可选链

代码语言:javascript
复制
const result = data?.mdx

条件渲染

代码语言:javascript
复制
{ data  &&
  return (
      <Layout>
    ...
}

编辑

如果你在尝试之后还在挣扎,也许你应该,而不是摧毁道具,控制台记录所有的道具,

代码语言:javascript
复制
const Post = (props) => {
    console.log(props)

检查通过的道具的形状是否与您预期的一样。

如果这也失败了,您可以尝试检查浏览器上的网络选项卡,并确定您是否实际从gql接收数据。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71555979

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档