Next-intl客户端组件useTranslations返回键名而非翻译内容求助
客户端组件使用next-intl的useTranslations返回键名而非翻译文本的问题排查
在客户端组件中调用useTranslations时,始终返回键名而非对应的翻译文本,但该功能在服务端组件中可正常工作。以下是相关代码及排查修复方案:
相关代码
ModalPaymentMethod.tsx
import { useTranslations } from "next-intl"; export const ModalPaymentMethod = () => { const t = useTranslations("PaymentMethod"); console.log(t("trigger")); return ( <AlertDialog> <AlertDialogTrigger className="bg-gradientPrimary hover:shadow-sm hover:shadow-default/90 text-gray-100 shadow hover:bg-defaultbutton/90 font-poppins font-medium p-2 rounded-2xl"> Payment Method {t("trigger")} </AlertDialogTrigger> <AlertDialogContent> <AlertDialogHeader> <AlertDialogTitle> What payment methods are available? </AlertDialogTitle> <AlertDialogDescription> <p> The site uses the stripe payment gateway, no payment information passes through the website. It is therefore possible to pay via PayPal or credit card. </p> <div className="flex flex-row items-center justify-center gap-8"> <FaCcStripe className="h-6 w-6" /> <FaPaypal className="h-6 w-6" /> <CiCreditCard1 className="h-6 w-6" /> </div> </AlertDialogDescription> </AlertDialogHeader> <AlertDialogFooter> <AlertDialogCancel>Close</AlertDialogCancel> </AlertDialogFooter> </AlertDialogContent> </AlertDialog> ); };
en.json
"PaymentMethod": { "trigger": "Payment Method", "title": "What payment methods are available?", "description": "The site uses the stripe payment gateway, no payment information passes through the website. It is therefore possible to pay via PayPal or credit card.", "test": "test" },
i18n.ts
import { notFound } from "next/navigation"; import { getRequestConfig } from "next-intl/server"; // Can be imported from a shared config export const locales = ["en", "fr"]; 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, }; });
next.config.js
/** @type {import('next').NextConfig} */ const createNextIntlPlugin = require('next-intl/plugin'); const withNextIntl = createNextIntlPlugin(); const nextConfig = { images: { remotePatterns: [ { protocol: "https", hostname: "utfs.io", port: "", pathname: "/**", }, { protocol: "https", hostname: "avatars.githubusercontent.com", port: "", pathname: "/**", }, ], }, reactStrictMode: false, webpack: (config) => { config.resolve.alias.canvas = false; return config; }, } module.exports = withNextIntl(nextConfig)
排查及修复步骤
添加客户端组件指令
Next.js 13+ App Router默认组件为服务端组件,useTranslations是客户端钩子,必须在标记为客户端的组件中使用。在ModalPaymentMethod.tsx顶部添加'use client';指令:'use client'; import { useTranslations } from "next-intl"; // 其余代码保持不变确保客户端组件被
NextIntlClientProvider包裹
服务端组件通过getRequestConfig获取翻译消息,但客户端组件需要通过NextIntlClientProvider注入翻译上下文。在locale布局组件(如app/[locale]/layout.tsx)中添加该Provider:import { NextIntlClientProvider } from 'next-intl'; import { getMessages } from 'next-intl/server'; import { ReactNode } from 'react'; export default async function LocaleLayout({ children, params: { locale } }: { children: ReactNode; params: { locale: string }; }) { const messages = await getMessages({ locale }); return ( <html lang={locale}> <body> <NextIntlClientProvider locale={locale} messages={messages}> {children} </NextIntlClientProvider> </body> </html> ); }修复翻译文件语法错误
你的en.json代码片段中PaymentMethod对象末尾有多余逗号,若这是文件最后一个键会导致JSON解析错误,需删除该逗号,确保JSON格式合法。
内容的提问来源于stack exchange,提问作者Thomas A
相关产品推荐
相关产品推荐

