getFixedT 在react-i18next 中无法按预期工作

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

我正在尝试在 React 应用程序中使用 useTranslation,并且我也想引用一种固定语言。 useTranslation t 函数按预期随浏览器变化,但固定语言始终返回英语。

行为如下所示:codesandbox应用程序在这个项目中,我得到了两个固定的t函数“en-US”和“fr”。两者都返回英文翻译。

在我使用的codesandbox中:

import { i18n } = useTranslation()

然后后来

i18n.getFixedT(lng)

我也使用过

i18next.getFixedT(lng)
,它具有相同的行为。

i18next react-i18next
1个回答
0
投票

这是预期的行为。如果未加载,getFixedT 不会加载语言。推荐的方法似乎是检查语言是否已经加载:

if (!i18n.hasResourceBundle(lng, "translation")){
    i18n.loadLanguages(lng, (err: unknown) => {
        if (err instanceof Error) {
            console.error("Error loading language: " + err.message)
        } else {
            const newDocT = i18n.getFixedT(lng)
            //.... use newDocT
        }
    })
} else {
    const newDocT = i18n.getFixedT(lng)
    //.... use newDocT
}

或者有一个新功能,允许将语言传递到 useTranslation 中(但这是一个 Hook,不能在 useEffect 或其他 Hook 内部使用)

const { t } = useTranslation('translation', { lng })

您可以在issue 1637

中阅读相关内容
© www.soinside.com 2019 - 2024. All rights reserved.