You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中如何跨页面获取URL的动态路由参数值

Next.js动态路由参数获取失败解决方案

问题原因

  • 跳转路径不匹配:当前<Link>组件的href设置为category/fitness/25,和目标动态路由store/[storeId]完全不对应,不会命中目标页面,自然无法拿到参数。
  • 参数名拼写错误:动态路由文件名为[storeId],取值时错误写为storId(少了字母e),导致取不到对应值。

修正方案

1. 修改MenuApi.js跳转路径

如果你要跳转至store页面并传递25作为storeId,将href改为/store/25即可;如果是从遍历的menu项中取动态id,使用模板字符串拼接即可,示例代码如下:

import React, { Component } from 'react'; 
import { Grid, Image } from "semantic-ui-react";
import Link from 'next/link';
 function MenuApi(props) {
   return (
         <Grid className="home-icon">
      <Grid.Row centered doubling columns={8} mobile>
        {props.menu.map((x, i) => (
          <Grid.Column centered key={i} style={{width: "9%!important"}}> 
            {/* 路径替换为store对应的动态路由 */}
            <Link href={`/store/${x.store_id || 25}`}>
              <Image src={x.image} alt=""/>
            </Link> 
            <Link href={`/store/${x.store_id || 25}`}>
              <p >{x.store_name}</p>
            </Link>
          </Grid.Column>
        ))}
      </Grid.Row>
    </Grid>
   )
 }

export default MenuApi;

注:原代码中Style属性首字母大写不符合React规范,已修正为小写style,值改为对象写法。

2. 修改store/[storeId].js参数取值代码

修正参数名拼写错误即可:

import {useRouter} from 'next/router';
function Store()
{
    const router=useRouter();
    // 修正参数名拼写,和路由文件名的动态参数保持一致
    const route=router.query.storeId;
    return(
        <h1>Store{route}</h1>
    )
}
export default Store;

内容的提问来源于stack exchange,提问作者karthik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 08:57:01