我如何在reactJS应用中的mobx存储中访问intl.formatMessage()?]

问题描述 投票:0回答:1

我有两个名称分别为'en.json'

'fr.json'的JSON文件,其中包含所有翻译。

en.json

{ "General.LearnMore": "Learn More" }

我有一个mobx存储(.ts文件),并且我想访问该类中的intl.formatMessage()

在功能组件中更容易。我可以使用useIntl()挂钩,但是如何在存储文件(非组件)中执行同样的操作。

当我在存储文件中编写以下代码时:

const messages = defineMessages({
  SMS: {
    id: 'General.LearnMore',
  },
});

const cache = createIntlCache();
const locale = localStorage.getItem('locale')!;
const intl = createIntl({ locale, messages: {} }, cache);
console.log(intl.formatMessage({ id: 'General.select' }));
console.log(intl.formatMessage({ id: messages.sms.id }));

它给出此错误:

enter image description here

我所缺少的,如何解决?请帮忙!

我有两个JSON文件,名称分别为'en.json'和'fr.json',具有所有翻译。 en.json {“ General.LearnMore”:“了解更多”}我有一个mobx商店(.ts文件),我想访问int ....

reactjs mobx react-intl
1个回答
0
投票

createIntl中,您将一个空对象传递给messages,因此intl找不到ID。

© www.soinside.com 2019 - 2024. All rights reserved.