我正在为我的应用程序创建一个语言转换程序。到目前为止,我可以支持4种语言(英语en、西班牙语sp、法语fr和阿拉伯ar)。我已经将所有语言属性文件转换为JSON,并且可以将这些文件导入我的.jsx文件中。然而,当涉及到语言设置时,我遇到了一些问题。
例如:我有这一行代码:<h1>{messages.en["user.userprofile"]}</h1>,这将翻译成用户配置文件。如果我将语言转换为法语<h1>{messages.fr["user.userprofile"]}</h1>,我将得到:Profil‘’utilisateur。
我不是对语言进行硬编码,而是让它动态地改变。我正在使用Redux加载用户配置文件。
const defaultLanguage = useSelector(
(state) => state.profileReducer.profile.language || []
);
...
<h1>{messages[defaultLanguage]["user.userprofile"]}</h1>我想要在页面上加载defaultLanguage。例如,如果用户的语言是英语,defaultLanguage将被设置为en。然而,当我这样做时,我会得到一个白屏幕和这个错误:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'user.userprofile')
at UserProfileNew (UserProfileNew.jsx?e01f:146)
at renderWithHooks (react-dom.development.js?61bb:14985)
at mountIndeterminateComponent (react-dom.development.js?61bb:17811)
at beginWork (react-dom.development.js?61bb:19049)
at HTMLUnknownElement.callCallback (react-dom.development.js?61bb:3945)
at Object.invokeGuardedCallbackDev (react-dom.development.js?61bb:3994)
at invokeGuardedCallback (react-dom.development.js?61bb:4056)
at beginWork$1 (react-dom.development.js?61bb:23964)
at performUnitOfWork (react-dom.development.js?61bb:22776)
at workLoopSync (react-dom.development.js?61bb:22707)但是,如果我将h1标记注释掉,并将console.log用于defaultLanguage,我会注意到它打印了5次。在前两次中,defaultLanguage设置为[]。然后,在最后3次中,defaultLangauge被设置为从Redux加载的用户的语言值。如何在页面加载时进行初始化,使其不会被未定义?我是遗漏了什么,还是需要改变我在h1标记中编写h1的方式?
发布于 2021-12-13 21:49:56
实际上你的问题不在Redux。
当您试图从messages.en["user.userprofile"]获得值时,假设您从messages.en.user.userprofile获得了值,但没有,它不是这样工作的-- JS认为它是通过键user.userprofile从对象获取值的,而JS的对象结构是
{
'messages': {
'en': {
'user.userprofile': {
}
}
}
}对于您来说,最简单、最便宜的解决方案是使用来自房客的方法房客或任何其他类似的实用程序库。这样你就可以写
get(messages.en, 'user.userprofile', [])并确保通过组合键获得值。
https://stackoverflow.com/questions/70340714
复制相似问题