如何正确使用 react-i18next 等待翻译?

11

我使用react-18next在我的React应用程序中加载翻译。我遇到一个问题,就是让我的应用程序等待翻译完成。这会在许多情况下破坏我们在Jenkins上的测试,因为它们正在搜索已翻译的键。

i18n.tsx:

i18n
.use(initReactI18next)
.init({
  resources, // set ressources to be used
  lng: "en", // set default language
  keySeparator: false, 
  interpolation: {
    escapeValue: false
  },
  react: {
    useSuspense: false,
  }
});

注意:我尝试过使用Suspense和不使用Suspense,useSuspense标志与尝试匹配(对于Suspense,默认为true)。
使用ready的尝试:
const SiteLabel: React.FunctionComponent<ISiteLabelProps> = (props) => {
  const { t, ready } = useTranslation(undefined, {
    useSuspense: false
  });

  const getTo = (): string => {
    return "/" + props.module.toLowerCase();
  }

  const getLabel = (): string => {
    return props.module.toLowerCase() + ":GEN_PAGETITLE";
  }

  if(!ready)
    return (<div>Loading Content...</div>);

  return (
      <ConfirmLink
        content={t(getLabel())}
        dirty={props.dirty}
        setDirty={props.setDirty}
        className={Styles.label + " id-btn-riskshield"}
        to={getTo()}
        toState={null}
      />
  );
}

export default SiteLabel;

使用Suspense尝试:

const SiteLabel: React.FunctionComponent<ISiteLabelProps> = (props) => {
  const { t } = useTranslation();

  const getTo = (): string => {
    return "/" + props.module.toLowerCase();
  }

  const getLabel = (): string => {
    return props.module.toLowerCase() + ":GEN_PAGETITLE";
  }
    
  return (
      <Suspense fallback={<div>Loading...</div>}
      <ConfirmLink
        content={t(getLabel())}
        dirty={props.dirty}
        setDirty={props.setDirty}
        className={Styles.label + " id-btn-riskshield"}
        to={getTo()}
        toState={null}
      />
      </Suspense>
  );
}

export default SiteLabel;

对我来说,两个版本似乎都不起作用,我可以看到翻译键仅显示了一瞬间。我需要深入到实际编写翻译而不是传递到下一个属性的点,或者我犯了什么错误?我没有使用next.js进行构建/部署。我希望在app.tsx中直接使用全局解决方案。

2个回答

3
也许这可以帮到你:https://www.i18next.com/overview/api#init 我使用回调函数在我的应用组件中设置“所有翻译已经加载完成”的状态。
i18n
.use(initReactI18next)
.init(
  interpolation: { 
    escapeValue: false
  },
  fallbackLng: "en",
  react: {
    useSuspense: false,
  }, () => {
    setTranslationsLoaded(true);
  });

export const App = () => {
  const [translationsLoaded, setTranslationsLoaded] = useState(false)
  //...
  return (
    translationsLoaded ? <MyAppContent /> : <MySpinnerOrSomething />
  )
}

1

尝试使用wait选项

react: { wait: true, useSuspense: false }


1
此已被弃用。 - Kevin Johnson
@KevinJohnson useSuspense: false 仍然可用。 - funky-nd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接