【问题标题】:proper getServerSideProps syntax for Typescript next.js + i18nTypescript next.js + i18n 的正确 getServerSideProps 语法
【发布时间】:2021-12-16 21:43:47
【问题描述】:

我正在为 NextJS Typescript 项目中的 next-i18next 集成而苦苦挣扎 - 几乎没有任何最近的示例。我已经配置了国际化路由,但只要 getServerSideProps 语法困扰我,我就无法正确设置 i18next。

我对 Typescript 了解不多,也不熟悉类型声明。

代码如下所示,大部分是从 next-i18next 文档中复制而来的:

### index.tsx

// rest of index.tsx...

export const getServerSideProps: GetServerSideProps = async ({locale}) => ({
  props: {
    ...await serverSideTranslations(locale, ['common', 'header']),
  },
})

export default Home

我的 IDE 中出现关于“语言环境”的错误。 即使我正在使用 getServerSideProps,我什至不确定它是否是大多数静态项目的最佳解决方案,但如果我最终计划一个 SSR,我似乎无法避免它。提供正确翻译内容的简单方法 + 具有匹配的 URL 区域设置会很棒。

【问题讨论】:

  • “我的 IDE 中出现关于“locale”的错误” - 您看到的错误是什么?

标签: typescript next.js i18next next-i18next


【解决方案1】:

locale 的输入错误是正确的,因为在没有设置 i18n 时它可以为空。请参阅此处的讨论:https://github.com/isaachinman/next-i18next/issues/1307

有多种方法可以处理这个问题

  1. 将语言环境转换为字符串
export const getServerSideProps: GetServerSideProps = async ({ locale }) => ({
  props: {
    ...await serverSideTranslations(locale as string, ['common', 'header']),
  },
})
  1. 定义您自己的 GetServerSideProps 类型,其中 locale 不是可选的并使用该类型。
type CustomGetServerSideProps<
  P extends { [key: string]: any } = { [key: string]: any },
  Q extends ParsedUrlQuery = ParsedUrlQuery
> = (context: GetServerSidePropsContext<Q>) => Promise<GetServerSidePropsResult<P>>

type GetServerSidePropsContext<Q extends ParsedUrlQuery = ParsedUrlQuery> = {
  req: IncomingMessage & {
    cookies: NextApiRequestCookies
  }
  res: ServerResponse
  params?: Q
  query: ParsedUrlQuery
  preview?: boolean
  previewData?: PreviewData
  resolvedUrl: string
  locale: string // This is where the magic happens.
  locales?: string[]
  defaultLocale?: string
}

export const getServerSideProps: CustomGetServerSideProps = async ({ locale }) => ({
  props: {
    ...await serverSideTranslations(locale, ['common', 'header']),
  },
})

我自己使用第二个选项,因为这样我就不必一直转换同一个变量,这也已经是一个字符串了。

【讨论】:

    【解决方案2】:
    import { useTranslation } from 'next-i18next'
    import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
    .....
    //try cxt or context (or locale) variables
    export const getServerSideProps: GetServerSideProps = async (ctx) => ({
          props: {
            ...await serverSideTranslations(ctx.locale, ['common', 'header']),
          },
        })
        
    export default Home
    

    如果不起作用,请通知我,我将分享我的解决方案。

    【讨论】:

      【解决方案3】:

      根据示例,我也想出尝试访问 { locale },但在 getServerSideProps 中显示为空。

      使用建议的上下文(感谢@illia chill)就像一种魅力。

      由于我已经在使用上下文对象 - 将语言环境作为属性访问是一个简单的解决方案。 (不能评论,所以需要像这样重新迭代;))

      【讨论】:

      • 你能澄清一下吗?我认为我对正确答案的重复没有足够的深度,因为我确实明确说明了什么没有,什么有效..只是没有代码示例..
      猜你喜欢
      • 2021-10-16
      • 2023-02-06
      • 2020-12-13
      • 2018-05-14
      • 2021-11-11
      • 2021-11-14
      • 2020-10-01
      • 2021-09-26
      • 1970-01-01
      相关资源
      最近更新 更多