next.js之动态路由

整体逻辑

how-to-dynamic-routes

getStaticPaths

  • 需要使用getStaticPaths返回一个对象,其中path包含动态路由所有的可能值

  • ```js
    export async function getStaticPaths() {

      const paths = getAllPostIds()
      return {
          paths,
          fallback: false,
      }
    

    }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33

    ### fallback

    如果[`fallback`是`false`](https://www.nextjs.cn/docs/basic-features/data-fetching#fallback-false),则任何未返回的路径[`getStaticPaths`](https://www.nextjs.cn/docs/basic-features/data-fetching#getstaticpaths-static-generation)都将产生**404 页面**。

    如果[`fallback`为`true`](https://www.nextjs.cn/docs/basic-features/data-fetching#fallback-true),则[`getStaticProps`](https://www.nextjs.cn/docs/basic-features/data-fetching#getstaticprops-static-generation)更改行为:

    - 返回的路径[`getStaticPaths`](https://www.nextjs.cn/docs/basic-features/data-fetching#getstaticpaths-static-generation)将在构建时呈现为 HTML。
    - 还没有在生成时生成的路径将**不会**导致 404 页。相反,Next.js 将在对此类路径的第一个请求时提供页面的“后备”版本。
    - 在后台,Next.js 将静态生成请求的路径。对同一路径的后续请求将服务于生成的页面,就像在构建时预渲染的其他页面一样。

    ### 通配路由

    在文件名中使用`...`,可匹配所有具备前置路径的文件

    - `pages/posts/[...id].js` matches `/posts/a`, but also `/posts/a/b`, `/posts/a/b/c` and so on.

    - 需要返回的匹配为数组

    ```js
    export async function getStaticPaths() {
    const paths = [
    {
    params: {
    id: ['a', 'b', 'c'],
    },
    },
    ]
    return {
    paths,
    fallback: false,
    }
    }

404page

创建/pages/404.js

Author: liuarui
Link: https://liuarui.github.io/2021/04/26/框架/next.js/动态路由/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.