# next-动态路由

在react中路由可以写成 /b/:id,那么在next中如何实现呢?

import { Button } from "antd"
import Link from "next/link"
import Router from "next/router"

const Index = ({ }) => {
    function gotoB() {
        Router.push({
            pathname: "/b",
            query: {
                id: 2
            }
        }, "/b/2")
    }
    return <div>
        <Link href="/b?id=2" as="/b/2">
            <Button >b page</Button>
        </Link>
        <Button onClick={gotoB}>go b</Button>
    </div>
}

export default Index
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

警告

在前端渲染时这么做是没有问题的,可是我们在B页面 按下F5 就会发现报404了,因为在后端渲染我们是找不到/b/2这个页面的

# server中处理动态路由

const Koa = require("koa")
const Router = require("koa-router")
const next = require("next")

const dev = process.env.NODE_ENV !== "production"
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
    const server = new Koa();
    const router = new Router();

    router.get("/b/:id", async (ctx) => {
        const id = ctx.params.id;
        await handle(ctx.req, ctx.res, {
            pathname: "/b",
            query: { id }
        })
    })
    server.use(router.routes())
    server.use(async (ctx, next) => {
        await handle(ctx.req, ctx.res);
        ctx.respond = false;

    })
    // server.use(router.routes())
    server.listen(3000, () => {
        console.log("koa serve 启动 3000")
    })
})
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

在 server中我们需要这么处理动态路由,那么在前端,和服务端都可以进行跳转了