【问题标题】:Pass data from dynamic page to persistent <Layout>{children}</Layout> component in Next.js将数据从动态页面传递到 Next.js 中的持久 <Layout>{children}</Layout> 组件
【发布时间】: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


【解决方案1】:
const Page = ({title, posts}) => {
  return <Layout title={title}>
    // include posts here with something like <Post/>
  </Layout>
}

...

export const getStaticProps = async () => {
  // pass title and posts to page
}

您应该将标题传递给页面,然后包含布局,然后将帖子包含为布局的子项。

【讨论】:

  • 每次我使用布局链接导航时,这不会导致重新呈现布局吗?
  • 我不确定“布局链接”是什么意思,但 getStaticProps 在页面生成(或通过重新验证重新生成)时只被调用一次。它会在客户端重新渲染东西,但这就是 react 的工作原理,除非需要(比如状态更新),否则它不会重新渲染它。
猜你喜欢
  • 2020-06-12
  • 1970-01-01
  • 2017-03-19
  • 2016-03-03
  • 2021-11-07
  • 2022-07-22
  • 2023-02-12
  • 2021-06-30
  • 1970-01-01
相关资源
最近更新 更多