我可以通过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}
似乎更容易出错。