如何在Gatsby主页添加新组件?解决重复默认导出错误
问题根源
你在pages/index.js里同时写了两个默认导出:export default BlogIndex和export default NewSectionIndex,而JavaScript规定每个模块只能有一个默认导出,这就是报错Only one default export allowed per module.的原因。
正确解决方案
1. 先修正src/components/newSection.js
你的新组件不需要嵌套Layout(原主页的BlogIndex已经用了Layout,重复嵌套会导致页面出现多份导航/页脚等布局元素):
import React from "react" export default function NewSection({ children }) { return ( <section className="new-section"> <p>New Section</p> {/* 渲染传入的子内容 */} {children} </section> ) }
2. 修改pages/index.js
删除你添加的NewSectionIndex函数定义和第二个export default NewSectionIndex,直接把NewSection组件嵌入到原有的BlogIndex组件的JSX结构中即可:
import * as React from "react" import { Link, graphql } from "gatsby" import Bio from "../components/bio" import Layout from "../components/layout" import Seo from "../components/seo" // 仅保留组件导入 import NewSection from "../components/newSection" const BlogIndex = ({ data, location }) => { const siteTitle = data.site.siteMetadata?.title || `Title` const posts = data.allMarkdownRemark.nodes if (posts.length === 0) { return ( <Layout location={location} title={siteTitle}> <Bio /> {/* 把新板块放在这里 */} <NewSection /> <p> No blog posts found. Add markdown posts to "content/blog" (or the directory you specified for the "gatsby-source-filesystem" plugin in gatsby-config.js). </p> </Layout> ) } return ( <Layout location={location} title={siteTitle}> <Bio /> {/* 示例:放在Bio和文章列表之间 */} <NewSection>这里是自定义的子内容</NewSection> <ol style={{ listStyle: `none` }}> {/* 原有文章列表渲染代码 */} {posts.map(post => { const title = post.frontmatter.title || post.fields.slug return ( <li key={post.fields.slug} className={`post-section`}> <article className="post-list-item" itemScope itemType="http://schema.org/Article" > <header> <h2> <Link to={post.fields.slug} itemProp="url"> <span itemProp="headline">{title}</span> </Link> </h2> <small className={"post-list-date"}>{post.frontmatter.date}</small> </header> <section> <p dangerouslySetInnerHTML={{ __html: post.frontmatter.description || post.excerpt, }} itemProp="description" /> </section> </article> </li> ) })} </ol> {/* 也可以放在文章列表底部 */} <NewSection>主页底部的新板块</NewSection> </Layout> ) } // 仅保留一个默认导出 export default BlogIndex /** * Head export to define metadata for the page */ export const Head = () => <Seo title="All posts" /> export const pageQuery = graphql` query { site { siteMetadata { title } } allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) { nodes { excerpt fields { slug } frontmatter { date(formatString: "MMMM DD, YYYY") title description } } } } `
3. 验证效果
修改完成后重启gatsby develop,就能在主页的对应位置看到新添加的板块了。
内容的提问来源于stack exchange,提问作者dmxt
相关产品推荐
相关产品推荐

