首页 > 解决方案 > Gatsby 不渲染组件

问题描述

我正在尝试使用导航、页脚和组件构建简单的页面,它们之间应该呈现哪些内容取决于导航。不幸的是,只有 Home 工作正常(存在导航和页脚)。当我单击导航中的任何其他链接时,Gatsby 仅渲染具有内容的组件,而没有导航和页脚(例如,仅 AboutUs)。

我的 index.js 代码:

import React from "react";
import { Router } from "@reach/router";

{* import of other components *}

const App = () => (
    <div>
        <Nav />
        <Router>
            <Home path="/" />
            <AboutUs path="about" />
            <Projects path="projects" />
            <Join path="join" />
            <Contact path="contact" />
        </Router>
        <Footer />
    </div>
);

export default App;

我的 Nav.js 组件看起来像这样:

import React from "react";
import { Link } from "gatsby";

import logo from "./assets/logoMain.svg";

const Nav = () => {
    const navNames = [
        { text: "about us", link: "about" },
        { text: "incoming trips", link: "travels" },
        { text: "join us", link: "join" },
        { text: "contact", link: "contact" },
    ];

    const navLinks = navNames.map((item) => (
        <Link to={item.link} key={item.link}>
            <span>{item.text}</span>
        </Link>
    ));

    return (
        <header>
            <Link to="./">
                <img src={logo} alt="Logo" />
            </Link>
            <div>{navLinks}</div>
        </header>
    );
};

export default Nav;

标签: reactjsgatsbyreach-router

解决方案


默认情况下,在 Gatsby 中,所有页面都应该从<Layout>组件扩展,因此,如果您在组件中创建这样的 React 结构<Layout>

const Layout = ({ children }) => {
  const data = useStaticQuery(graphql`
      query getSiteTitle {
          site {
              siteMetadata {
                  title
              }
          }
      }
  `);

  return  <section>
    <Header />
    <main>{children}</main>
    <footer>
      © {new Date().getFullYear()}, Built by
      {`your name`}
    </footer>
  </section>;
};

从该组件扩展的每个页面都将包含共享组件(页眉、页脚等)。例如,在您的AboutUs页面上:

const AboutUs = ({ data }) => {
  return <Layout>
    <h1>I'm your about us page</h1>    
  </Layout>;
};

在上面的代码段中,因为<Header><footer>存在于页面中,<Layout>所以它也将出现在AboutUs页面中。


推荐阅读