【发布时间】:2021-10-15 19:59:29
【问题描述】:
我想在 Next.js 中使用持久布局,并从我的动态博客文章页面向它传递一些数据。
因此,例如拥有此代码(来自 next.js 文档):
// pages/posts/[id].js
function Post({ post }) {
return <p>{post.title}</p>;
}
// Trying to export the post title here
export const postTitle = ({ post }) => {
return post.title;
};
export async function getStaticPaths() {
// Call an external API endpoint to get posts
const res = await fetch("https://.../posts");
const posts = await res.json();
// Get the paths we want to pre-render based on posts
const paths = posts.map((post) => ({
params: { id: post.id },
}));
// We'll pre-render only these paths at build time.
// { fallback: false } means other routes should 404.
return { paths, fallback: false };
}
// This also gets called at build time
export async function getStaticProps({ params }) {
// params contains the post `id`.
// If the route is like /posts/1, then params.id is 1
const res = await fetch(`https://.../posts/${params.id}`);
const post = await res.json();
// Pass post data to the page via props
return { props: { post } };
}
export default Post;
如何获取该 {post.title} 并在我的持久布局组件中使用它,如下所示:
// SiteLayout.js
import React from "react";
import { postTitle } from "../../pages/posts/[id]";
// Main Page Wrapper
const SiteLayout = ({ children }) => {
return (
<>
{postTitle && <p>{postTitle}</p>}
<main className="layout">{children}</main>
</>
);
};
export default SiteLayout;
我已经花了几个小时试图完成这项工作,所以我非常感谢任何指点!谢谢!
【问题讨论】:
-
nextjs.org/docs/basic-features/layouts#per-page-layouts 具有能够读取布局组件中页面道具的模式。这有帮助吗?
-
@AKX 这样我可以通过 getLayout 函数将道具传递给布局吗? (编辑->)这似乎会尝试并在此处发布更新。谢谢!
-
成功了,非常感谢@AKX
标签: javascript reactjs next.js