0

我可以通过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 />级在加载翻译之前也会经历初始渲染。

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

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

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

4

1 回答 1

0

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

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

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

于 2019-03-08T09:27:35.450 回答