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

NextJS App目录结构下动态路由出现404错误求助

问题原因及解决方案

核心问题是你混用了Next.js Pages Router和App Router的规则,App Router的动态路由实现逻辑和Pages Router完全不同,导致路由无法匹配出现404。

1. 修正动态路由文件结构

App Router中,动态路由必须遵循目录+page.js的规则:

  • 创建目录 app/location/[city]
  • 在该目录下创建 page.js(文件名固定为page.js,不能用[city].js)

2. 替换getServerSideProps逻辑

App Router不再支持getServerSideProps,获取路由参数有两种常用方式:

方式一:服务器组件(推荐,适合数据预取场景)

直接在组件参数中解构params:

// app/location/[city]/page.js
export default async function City({ params }) {
  const { city } = params;
  
  // 可在此添加天气数据获取逻辑,例如:
  // const weatherData = await fetch(`https://api.example.com/weather?city=${city}`).then(res => res.json());
  
  return (
    <div>
      <h1>City page</h1>
      <h2>{city}</h2>
    </div>
  );
}

方式二:客户端组件(适用于需要交互的场景)

使用useParams钩子获取参数:

// app/location/[city]/page.js
'use client';

import { useParams } from 'next/navigation';

export default function City() {
  const params = useParams();
  const city = params.city;

  return (
    <div>
      <h1>City page</h1>
      <h2>{city}</h2>
    </div>
  );
}

3. 确认Link组件导入

确保你的Link组件是从next/link导入的(App Router和Pages Router的Link导入路径一致,可再检查确认):

import Link from 'next/link';

完成以上修改后,重启开发服务器,点击链接即可正常跳转。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 06:55:16