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

Next.js 14使用next-intl切换语言时跳转到首页的问题

解决Next.js 14 + next-intl切换语言时跳转首页的问题

你的问题核心在于切换语言时直接导航到了新locale的首页,没有保留当前页面的路径结构。下面是具体的修复方案:

1. 修改LocalSwitcher组件,保留当前路径

关键是获取当前页面路径,仅替换locale前缀,而不是直接跳转到首页。修改后的代码如下:

"use client";

import { useRouter, usePathname } from "next/navigation";
import { useTransition } from "react";
import type { MenuProps } from "antd";
import { Dropdown, Space } from "antd";
import { GlobeAltIcon } from "@heroicons/react/24/outline";
import { useLocale } from 'next-intl'; // 引入next-intl的locale钩子

export default function LocalSwitcher() {
  const items: MenuProps["items"] = [
    { label: "🇺🇸 English", key: "en" },
    { label: "🇷🇺 Русский", key: "ru" },
    { label: "🇺🇿 O`zbek", key: "uz" },
  ];

  const router = useRouter();
  const pathname = usePathname(); // 获取当前页面完整路径
  const currentLocale = useLocale(); // 获取当前激活的locale
  const [isPending, startTransition] = useTransition();

  const onClick: MenuProps['onClick'] = ({ key }) => {
    const nextLocale = key;
    let newPath;

    // 处理路径:替换当前locale为新locale,首页特殊处理
    if (pathname === `/${currentLocale}` || pathname === '/') {
      newPath = `/${nextLocale}`;
    } else {
      newPath = pathname.replace(`/${currentLocale}`, `/${nextLocale}`);
    }

    startTransition(() => {
      router.replace(newPath);
    });
  };
  
  return (
    <span>
      <Dropdown
        menu={{ items, onClick }}
        trigger={["click"]}
      > 
        <Space>     
          <GlobeAltIcon className="h-6 w-6 cursor-pointer globe-icon"/>
        </Space>
      </Dropdown>
    </span>
  );
}

2. 简化中间件的matcher配置

你当前的matcher配置存在冗余,简化后可以避免路径匹配冲突:

import createMiddleware from 'next-intl/middleware';
 
export default createMiddleware({
  locales: ['en', 'ru', 'uz'],
  defaultLocale: 'en'
});
 
export const config = {
  // 匹配所有非API、非静态资源的路径
  matcher: ['/((?!api|_next|_vercel|.*\\..*).*)']
};

修复逻辑说明

  • 用usePathname获取当前页面的完整路径,比如/ru/profile
  • 用useLocale获取当前激活的语言标识,比如ru
  • 替换路径中的旧locale为新locale,得到/en/profile,再用router.replace跳转
  • 对首页做特殊处理,确保切换后仍指向对应语言的首页

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 00:05:22