从本地JSON文件创建动态路由nextjs 13

huangapple go评论81阅读模式
英文:

Creating dynamic routes from local json file nextjs 13

问题

我有一个本地的 JSON 文件,其中包含一个对象数组,例如:

projects.json

[
   {"id":0,
    "title":"这是标题",
    "info":"这是更多信息",
    "img":"www.imagelink.com"},
     ...
     ...
   {"id":10,
    "title":"这是标题",
    "info":"这是更多信息",
    "img":"www.imagelink.com"},
]

我的目标是映射这个对象并为每个对象创建一个单独的页面链接。目前我已经设置好了如下的结构,一个带有动态URL的链接,每个对象都有一个不同的链接。

Projects.tsx

<div className='projects-container'>
      {projectlist.map((project)=>{
        return(
            <Link href={`/${project.id}`}>
              <img src={project.img} alt="这是一张图片" />
            </Link>
        )
      })}
    </div>

我在想如何将所有属性传递给每个动态路由,以便用户单击页面时会被重定向到一个页面,其中包含如下所示的所有信息,作为示例。

[uniquepage]/page.tsx

export default function UniquePage() {
  return (
    <div>
      {projectlist.map(project=>{
        return(
          <p>ID:{project.id}</p>
          <p>标题:{project.title}</p>
          <p>信息:{project.info}</p>
        )
      })}
    </div>
  )
}

我遵循的所有指南都是基于从API获取数据和异步函数。由于JSON文件位于本地目录中,我不需要异步函数。

英文:

I have a local JSON file that is an array of objects such as:

projects.json

[
   {&quot;id&quot;:0,
    &quot;title&quot;:&quot;this is the title&quot;,
    &quot;info&quot;:&quot;here is more info&quot;,
    &quot;img&quot;:&quot;www.imagelink.com&quot;},
     ...
     ...
   {&quot;id&quot;:10,
    &quot;title&quot;:&quot;this is the title&quot;,
    &quot;info&quot;:&quot;here is more info&quot;,
    &quot;img&quot;:&quot;www.imagelink.com&quot;},
]

my goal is to map this object and have a separate page link for each one. Right now I have this as a set up. A link with a dynamic URL, distinct for each object.

Projects.tsx

&lt;div className=&#39;projects-container&#39;&gt;
      {projectlist.map((project)=&gt;{
        return(
            &lt;Link href={`/${project.id}`}&gt;
              &lt;img src={project.img} alt=&quot;this is an image&quot; /&gt;
            &lt;/Link&gt;
        )
      })}
    &lt;/div&gt;

I am having trouble figuring out how to pass all the props to each dynamic route, so that when the user clicks the page they will be directed to a page with all this information set up like this, for an example.

[uniquepage]/page.tsx

export default function UniquePage() {
  return (
    &lt;div&gt;
      {projectlist.map(project=&gt;{
        return(
          &lt;p&gt;ID Here:{project.id}&lt;/p&gt;
          &lt;p&gt;Title Here:{project.title}&lt;/p&gt;
          &lt;p&gt;Info Here:{project.info}&lt;/p&gt;
        )
      })}
    &lt;/div&gt;
  )
}

All the guides I follow are based off of getting data from APIs and async functions. Since the json file is in the local directory I do not need an async funciton.

答案1

得分: 1

你不能将props传递给页面,除非你使用一些复杂的路由方式,比如使用cookies或localStorage。

正确的方法是从相同的JSON文件中在你的详情页面中获取数据,使用uniquepage作为ID。如果具有该uniquepage的项目不存在,你将会抛出notFound(),导致404页面。

使用generateStaticParams来静态预构建页面。这不是必需的,但会加快页面加载速度。

project/page.tsx

import projectlist from '@/app/projects.json';
import Link from "next/link";

export default function Home() {
  return (
    <main>
      {projectlist.map((project) => (
        <Link key={project.id} href={`/${project.id}`}>
          <img src={project.img} alt="这是一张图片" />
        </Link>
      ))}
    </main>
  )
}

project/[uniquepage]/page.tsx

import projectlist from '@/app/projects.json';
import { notFound } from "next/navigation";

export async function generateStaticParams() {
  return projectlist.map((p) => ({
    uniquepage: p.id.toString(),
  }))
}

export default function UniquePage({ params: { uniquepage } }: { params: { uniquepage: string } }) {
  const project = projectlist.find(p => p.id.toString() === uniquepage);
  if (!project) {
    notFound();
  }

  return (
    <main>
      <p>ID在这里{project.id}</p>
      <p>标题在这里{project.title}</p>
      <p>信息在这里{project.info}</p>
    </main>
  )
}
英文:

You can't pass props to the page, not unless you go for some complicated route with cookies or localStorage.

Proper way is to fetch data in your detail page from the same json, using uniquepage as id. If the project with that uniquepage does not exists, you will throw notFound() that will result in 404 page.

Use generateStaticParams to prebuild pages statically. Not a requirement, but will speed up the loading.

project/page.tsx

import projectlist from &#39;@/app/projects.json&#39;
import Link from &quot;next/link&quot;;

export default function Home() {
  return (
    &lt;main&gt;
      {projectlist.map((project) =&gt; (
        &lt;Link key={project.id} href={`/${project.id}`}&gt;
          &lt;img src={project.img} alt=&quot;this is an image&quot; /&gt;
        &lt;/Link&gt;
      ))}
    &lt;/main&gt;
  )
}

project/[uniquepage]/page.tsx

import projectlist from &#39;@/app/projects.json&#39;
import {notFound} from &quot;next/navigation&quot;;

export async function generateStaticParams() {
  return projectlist.map((p) =&gt; ({
    uniquepage: p.id.toString(),
  }))
}

export default function UniquePage({params: {uniquepage}}: { params: { uniquepage: string } }) {
  const project = projectlist.find(p =&gt; p.id.toString() === uniquepage)
  if (!project) {
    notFound()
  }

  return (
    &lt;main&gt;
      &lt;p&gt;ID Here:{project.id}&lt;/p&gt;
      &lt;p&gt;Title Here:{project.title}&lt;/p&gt;
      &lt;p&gt;Info Here:{project.info}&lt;/p&gt;
    &lt;/main&gt;
  )
}

huangapple
  • 本文由 发表于 2023年7月10日 10:49:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76650404.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定