【发布时间】: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 的消息,因为使用 <NamespacesConsumer /> 的子代在加载翻译之前也会进行初始渲染。
我找到了三种方法来防止这种行为:
- 使用
contructor而不是componentDidMount来加载翻译。这将阻止初始渲染,但确保所有翻译在发生时都可用。 - 将
wait={true}传递给每个<NamespacesConsumer />,不会阻塞整个屏幕的初始渲染,但需要开发者记住将prop 传递给每个组件,因为它默认为false。 - 像这样覆盖
<NamespacesConsumer />的defaultProps:
NamespacesConsumer.defaultProps = {
wait: true,
}
这个问题的首选解决方案是什么?在我看来,不推荐使用构造函数,但要求所有开发人员指定 wait={true} 似乎更容易出错。
【问题讨论】:
标签: reactjs i18next react-i18next