0

我在 Next JS + React JS + Tailwind 中构建了一个单页应用程序,我从 firebase 加载了许多项目。

我在应用程序中使用 Firebase 的 docRef 作为 ID。现在我希望用户能够从 URL 中引用一个项目并与其他人共享。我将如何实施呢?

我研究过 Next.js 路由/动态路由和 React 路由器,但是因为这是我第一次使用 React 和 Next.js,所以我不知道从哪里开始。任何帮助深表感谢。谢谢!

4

1 回答 1

0

如果我理解正确:您有一个概述页面和详细信息页面。在路由方面,这看起来像:/overview/overview/${ID}

你应该看看https://nextjs.org/docs/basic-features/data-fetching#getstaticpaths-static-generation。更详细地说:

// pages/posts/[id].js

function Post({ post }) {
  // Render post...
}

// This function gets called at build time
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

在 getStaticPaths 中,您可以定义可用的动态路径。Next.js 将生成这些页面。在 getStaticProps 中,您传入从 getStaticPaths 返回的对象。在此函数的返回中,您传递了构建详细信息页面所需的所有信息/道具。

于 2021-08-20T10:00:19.540 回答