【问题标题】:Loading translations in constructor vs componentDidMount在构造函数与 componentDidMount 中加载翻译
【发布时间】:2019-03-08 09:11:29
【问题描述】:

我可以通过 i18n.addResources(['en', en, namespace]) 在组件(例如页面或 react-native 屏幕)中加载翻译块。

我本能地在 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 的消息,因为使用 &lt;NamespacesConsumer /&gt; 的子代在加载翻译之前也会进行初始渲染。

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

  • 使用contructor 而不是componentDidMount 来加载翻译。这将阻止初始渲染,但确保所有翻译在发生时都可用。
  • wait={true} 传递给每个&lt;NamespacesConsumer /&gt;,不会阻塞整个屏幕的初始渲染,但需要开发者记住将prop 传递给每个组件,因为它默认为false。
  • 像这样覆盖&lt;NamespacesConsumer /&gt;defaultProps
NamespacesConsumer.defaultProps = {
 wait: true,
}

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

【问题讨论】:

    标签: reactjs i18next react-i18next


    【解决方案1】:

    我在the documentation 中发现,您可以在初始化i18n 对象时默认waittrue

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

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

    【讨论】:

      猜你喜欢
      • 2018-08-23
      • 2022-01-09
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      相关资源
      最近更新 更多