首页 > 解决方案 > 在构造函数与 componentDidMount 中加载翻译

问题描述

我可以通过i18n.addResources(['en', en, namespace]).

我本能地在componentDidMount方法中这样做了,这通常是此类操作的首选方法,并创建了一个小型实用程序组件来加载我的翻译文件。

class NamespaceLoader extends React.Component<NamespaceLoaderProps> {
  public componentDidMount() {
    this.props.resources.map(resource =>
      this.props.i18n.addResources(...resource),
    )
  }

  public render() {
    return this.props.children
  }
}

但是,通过这样做,我在加载翻译之前等待初始渲染。这会触发i18next::translator: missingKey fr HomeRecord titleFieldLabel titleFieldLabel控制台中的消息,因为使用的子<NamespacesConsumer />级在加载翻译之前也会经历初始渲染。

我找到了三种防止这种行为的方法:

NamespacesConsumer.defaultProps = {
 wait: true,
}

这个问题的首选解决方案是什么?在我看来,使用构造函数不是推荐的做法,但通过要求他们指定来给所有开发人员增加负担wait={true}似乎更容易出错。

标签: reactjsi18nextreact-i18next

解决方案


我在文档中发现初始化对象时可以默认wait使用:truei18n

i18n
  .use(languageDetector)
  .use(reactI18nextModule)
  .init({
    //...
    react: {
      wait: true,
    },
  })

这可能是防止控制台中出现任何警告的最佳解决方案。


推荐阅读