reactjs - 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;
解决方案
默认情况下,在 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
页面中。
推荐阅读
- java - 无法使用 StringBuilder 替换字符串中的“null”字符
- c - 有没有办法在 C 中更改具有动态大小的字符串数组的特定索引的值?
- javascript - 按对象的子数组最大日期对对象数组进行排序
- reactjs - 与 Redux Thunk 结合使用时,React Native Redux Persist 不持久化状态
- asp.net-core-mvc - 公共托管服务器中的 ASP.NET Core 3.1 部署问题
- bash - 根据特定字符查找和重命名目录
- cocoa - NSApplication 箭头键的响应链
- python - How to graph a list with days ( y: number of days x:day)
- android - How to send data from Multiple Fragments to single activity on FAB button click
- java - I'm getting a GnssLocationProvider: 'Wakelock acquired' followed by 'Wakelock released' logcat error on my android studio app