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

Next.js动态路由与next-i18next兼容异常求助

问题解决建议

1. 修复非默认语言动态路由404问题

你的getStaticPaths仅生成了默认语言(it)的静态路径,未为英文(en)生成对应路径,导致非默认语言下访问动态路由返回404。修改getStaticPaths,为每个项目、每个语言生成静态路径:

export async function getStaticPaths() {
  const projectsList = await projects.find();
  
  // 为每个项目遍历所有语言,生成对应路径
  const paths = projectsList.flatMap((project) => 
    ["it", "en"].map((locale) => ({
      params: { id: project.id + "" },
      locale, // 指定当前路径对应的语言
    }))
  );

  return {
    paths,
    fallback: false,
  };
}

2. 修复路由跳转参数不匹配问题

你当前的动态路由文件是[id].tsx,但跳转时传递的是slug参数,参数不匹配会引发切换语言时的错误。

方案1:匹配现有[id].tsx路由

修改projects/index.tsx中的跳转逻辑,传递id参数:

return <button onClick={() =>
        router.push({
          pathname: `/projects/[id]`, // 对应动态路由文件名
          query: { id: project.id }, // 传递id参数,而非slug
        })
      }>Read more</button>

方案2:改用slug作为路由参数

若想使用slug,将动态路由文件重命名为[slug].tsx,并修改以下代码:

// [slug].tsx中的getStaticPaths
export async function getStaticPaths() {
  const projectsList = await projects.find();
  const paths = projectsList.flatMap((project) => 
    ["it", "en"].map((locale) => ({
      params: { slug: project.slug },
      locale,
    }))
  );
  return { paths, fallback: false };
}

// [slug].tsx中的getStaticProps
export async function getStaticProps({ locale, params }: { locale: string; params: { slug: string } }) {
  const project = await projects.findOne({ slug: params.slug });
  // 剩余逻辑保持不变
}

同时修改跳转逻辑:

router.push({
  pathname: `/projects/[slug]`,
  query: { slug: project.slug },
})

3. 修复语言切换时的路径错误

在详情页切换语言时,需保留当前路由参数并正确指定语言,避免出现missing query values错误。使用useTranslation和useRouter实现正确切换:

import { useTranslation } from 'next-i18next';
import { useRouter } from 'next/router';

const ProjectDetail = ({ project }) => {
  const { i18n } = useTranslation();
  const router = useRouter();

  const toggleLanguage = () => {
    const newLocale = i18n.language === 'it' ? 'en' : 'it';
    // 保留当前路径与参数,切换语言
    router.push(
      { pathname: router.pathname, query: router.query },
      undefined,
      { locale: newLocale }
    );
  };

  return (
    <button onClick={toggleLanguage}>
      {i18n.language === 'it' ? 'Switch to English' : 'Cambia in Italiano'}
    </button>
  );
};

4. 确认Next.js配置正确集成i18n

确保next.config.js中导入并使用了next-i18next.config.js的配置:

const { i18n } = require('./next-i18next.config');

module.exports = {
  i18n,
  // 其他Next.js配置
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:59:16