React-intl - 访问嵌套消息

2024-01-10

我正在尝试使用react-intl封装在应用程序内。该应用程序在服务器上呈现,因此我编写了一些代码来确定使用哪种语言并提供服务IntlProvider.

翻译提供于messages.js文件,它们看起来像这样:

export default {
  en: {
    message: '...some message',
    nested: {
      anotherMessage: '...another message',
    }
  }
  de: {
    // ...
  }
}

我所做的是这样的:

// import messages from './messages.js'
// Check the locale for the user (based on cookies or other things)
const locale = ...
// Get the required messages
const messagesForLocale= = messages[locale];
// Supply the messages to the IntlProvider
<IntlProvider locale={locale} messages={messagesForLocale}>
  // ...
</IntlProvider>

然后当我使用FormattedMessage组件我无法访问嵌套消息(anotherMessage),代码如下:

<FormattedMessage id="nested.anotherMessage" ... />

But message是可以访问的。

我有什么想法犯了错误,或者我在整个概念中遗漏了一些东西?


由于 React Intl v2 不再支持嵌套消息对象,因此消息需要压扁的 https://formatjs.io/docs/react-intl/upgrade-guide-2x/#flatten-messages-object.

export const flattenMessages = ((nestedMessages, prefix = '') => {
  if (nestedMessages === null) {
    return {}
  }
  return Object.keys(nestedMessages).reduce((messages, key) => {
    const value       = nestedMessages[key]
    const prefixedKey = prefix ? `${prefix}.${key}` : key

    if (typeof value === 'string') {
      Object.assign(messages, { [prefixedKey]: value })
    } else {
      Object.assign(messages, flattenMessages(value, prefixedKey))
    }

    return messages
  }, {})
})

// Use flattenMessages
<IntlProvider locale={locale} messages={flattenMessages(messagesForLocale)}>

refs:

  • https://github.com/yahoo/react-intl/wiki/Upgrade-Guide#flatten-messages-object https://github.com/yahoo/react-intl/wiki/Upgrade-Guide#flatten-messages-object
  • https://github.com/yahoo/react-intl/issues/162#issuecomment-139683466 https://github.com/yahoo/react-intl/issues/162#issuecomment-139683466
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React-intl - 访问嵌套消息 的相关文章