首页 > 解决方案 > 使用 next.js 中的钩子以编程方式进行动态导航

问题描述

我有一个基于 next.js 框架的应用程序,其中我使用材料表组件来处理项目中的表。这个库有一个名为 onRowClick 的 props,它反过来接受一个附加到列中每一行的原生 onClick 道具的函数。我现在想要得到的是一个动态链接,它将把用户带到点击时的适当页面。

在 next.js 中动态链接对我来说仍然有点不清楚,但到目前为止我已经尝试过:

//The class organizin paths in the application (simplified)
export default class Routes {
    public static PLAYERS = '/players';
    public static PLAYER = (id: number) => `${Routes.PLAYERS}/${id}`;
    public static PLAYER_SCHEME = `${Routes.PLAYERS}/[id]`;}

….

const router = useRouter();
//I am providing here a dynamic path scheme and as the second dynamic path parameter to be filled for each player separately
const redirect = async (id: number) => router.push(Routes.PLAYER_SCHEME, Routes.PLAYER(id));

…

//Passing function to the table
onRowClick={async (_, row) => (row?.id ? redirect(row.id) : undefined)}

一切都可能运作良好。但是,我Players在 Pages 文件夹中的组件正在根据来自 url 的 id 参数执行对 api 数据的请求。不幸的是,以这种方式将路由推送到路由器,两次渲染pages/Players/[id]组件,第一次在 params id 中得到一个 null 和下一个正确的 id。

TL;DR 当我无法使用 Link 组件时,在 next.js 中创建动态链接的正确方法是什么,因为它会破坏 app html 结构的语义。

标签: reactjsroutesnext.jsmaterial-table

解决方案


您可以使用 Next.js 中的路由器

import Router from 'next/router'

cosnt redirect = (url) => {
    Router.push(url)
}

例如:

Router.push('/login');
Router.push('/products/' + id);

推荐阅读