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

Next.js App Router:嵌套服务端组件获取params.lang的简便方案

避免Next.js服务端组件透传params.lang的方案

在Next.js App Router的服务端组件中,有两种可靠的方式可以避免逐层透传params.lang:

方法一:使用React Context(推荐)

通过创建服务端可用的Context,在顶层布局注入locale,嵌套组件直接取用:

  1. 创建Locale上下文
// app/locale-context.tsx
import { createContext, useContext } from 'react';

const LocaleContext = createContext<string | undefined>(undefined);

export function LocaleProvider({ children, locale }: { children: React.ReactNode; locale: string }) {
  return (
    <LocaleContext.Provider value={locale}>
      {children}
    </LocaleContext.Provider>
  );
}

export function useLocale() {
  const locale = useContext(LocaleContext);
  if (!locale) {
    throw new Error('useLocale必须在LocaleProvider内部使用');
  }
  return locale;
}
  1. 在顶层布局注入locale
    在路由目录(如app/[lang]/layout.tsx)的布局组件中,将params.lang传入Context:
// app/[lang]/layout.tsx
import { LocaleProvider } from './locale-context';

export default async function RootLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: { lang: string };
}) {
  return (
    <LocaleProvider locale={params.lang}>
      {children}
    </LocaleProvider>
  );
}
  1. 嵌套组件直接获取locale
    你的ShareButton组件可以直接通过useLocale获取,无需透传:
import { getDictionary } from "@/get-dictionary";
import { useLocale } from "../locale-context";

type Props = {
  link: string;
};

const ShareButton = (props: Props) => {
  const locale = useLocale();
  const dictionary = await getDictionary(locale);

  return <div>{dictionary.share}</div>;
};

export default ShareButton;

方法二:通过请求头解析路由参数

如果不想用Context,也可以通过next/headers获取请求头中的URL,解析出lang参数(依赖路由结构,灵活性稍差):

import { headers } from 'next/headers';
import { getDictionary } from "@/get-dictionary";

type Props = {
  link: string;
};

const ShareButton = (props: Props) => {
  const headersList = headers();
  const url = new URL(headersList.get('next-url') || '');
  // 假设路由结构为 /[lang]/xxx,取路径第一段作为locale
  const locale = url.pathname.split('/')[1];

  const dictionary = await getDictionary(locale);

  return <div>{dictionary.share}</div>;
};

export default ShareButton;

注意:方法二依赖固定的路由结构,如果后续路由规则变更,需要同步修改解析逻辑,不如Context方案稳定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 19:32:36