0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

速習App Router#5 ダイナミックセグメント・notFound.tsx・generateStaticParams

Last updated at Posted at 2024-02-27

はじめに

この記事は下記の講座で学んだ内容をまとめています。
理解が怪しい所があるので教えてくれるととても嬉しいです。

目次

1.速習App Router#1
2.速習App Router#2
3.速習App Router#3
4.速習App Router#4
5.速習App Router#5 <- この記事
6.速習App Router#6
7.速習App Router#7

ダイナミックセグメントについて

このようなpage.tsxがネストされているファイル構造を想定します。

app/blogs
├── page.tsx
    layout.tsx
    [blogId]
     └─ page.tsx
        not-found.tsx

http://localhost:3000/blogs -> app/layout.tsx + app/blogs/layout.tsx + app/blogs/page.tsx が描画される。

app/blogs/page.tsxapp/blogs/layout.tsxのchildrenの中に入ってラップされて、そのlayout.tsxapp/layout.tsxがラップされて描画されている。

http://localhost:3000/blogs/[blogId] -> app/layout.tsx + app/blogs/layout.tsx + app/blogs/[blogId]/page.tsx が描画される。

app/blogs/[blogId]/page.tsxapp/blogs/layout.tsxのchildrenの中に入ってラップされて、そのlayout.tsxapp/layout.tsxがラップされて描画されている。

このように、layout.tsxのchildrenに渡るpage.tsxだけをURLによって変更することで画面の一部だけ変更されるダイナミックセグメントを実装出来る。

notFound.tsx

コンポーネントの中で notFound()を実行するとそのpage.tsxの代わりにnot-found.tsxが描画されます。

/page.tsx
export default async function BlogDetailPage({ params }: PageProps) {
    const blog = await fetchBlog(params.blogId);
    console.log(blog);
    if (!blog) return notFound()
    
    return (
      <div className="mt-16 border-2 p-8">
      コンポーネント内でこのように記述します
      </div>
    )
  }

コンポーネント内でこのように記述します。
変数blogには動的なルーティングでフェッチしたデータが入っている想定です。

generateStaticParams

ダイナミックルーティングするページをSSGする時に使います。
Page RoutergetStaticPaths の App Router版です。

page.tsx
  export async function generateStaticParams() {
    const res = await fetch(`${process.env.url}/rest/v1/blogs?select=*`, {
      headers: new Headers({
        apikey: process.env.apikey as string,
      }),
    })
    const blogs: Blog[] = await res.json()
  
    return blogs.map((blog) => ({
      blogId: blog.id.toString(),
    }))
  }

このように記述します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?