当我更改语言时,next-intl 重定向到主页

问题描述 投票:0回答:1

我在我的 Next.js 项目中使用 next-intl。一切正常,除了当用户更改语言时,网页会更改语言并重定向到主页。如何才能让用户更改语言时不重定向到主页?

例如,假设我在页面 domain.com/ru/profile/data。当用户更改为英语时,页面应显示 domain.com/en/profile/data,但它会将我重定向到domain.com/en。

这是我的代码:

中间件.ts

import createMiddleware from 'next-intl/middleware';
 
export default createMiddleware({
  locales: ['en', 'ru', 'uz'],
 
  defaultLocale: 'ru',
});
 
export const config = {

  matcher: [
    '/((?!api|_next|_vercel|.*\\..*).*)',
    '/([\\w-]+)?/users/(.+)'
  ]
};

i18n.ts

import {notFound} from 'next/navigation';
import {getRequestConfig} from 'next-intl/server';
 
// Can be imported from a shared config
const locales = ['en', 'ru', 'uz'];
 
export default getRequestConfig(async ({locale}) => {
  // Validate that the incoming `locale` parameter is valid
  if (!locales.includes(locale as any)) notFound();
 
  return {
    messages: (await import(`../messages/${locale}.json`)).default
  };
});

标头.tsx

  <Link
      locale="en"
      href="/"
      onClick={() => setSelectedLanguage('en')} 
      className={classNames(
      active ? 'bg-gray-100 text-gray-900' : 'text-gray-700',
      'block px-4 py-2 text-sm'
      )}
     >
    <span className="fi fi-gb h-4"></span> English
   </Link>

P.S. 这里的解决方案对我不起作用。先谢谢你了

next.js internationalization next-intl
1个回答
0
投票

您实际上是在要求它去

href="/"
您期望什么?

  <Link
      locale="en"
      href="/"
      onClick={() => setSelectedLanguage('en')} 
     >
    English
   </Link>

重定向回同一页面。你可以使用

usePathname

"use client";

import {usePathname} from "@/navigation";

function LanguageSwitcher() {
  const pathname = usePathname();

  return (
  <Link
    locale="en"
    href={pathname}
   >
    English
  </Link>
  )
}
© www.soinside.com 2019 - 2024. All rights reserved.