react-intl - 访问嵌套消息

Anc*_*nek 8 javascript reactjs react-intl

我正在尝试react-intl在应用程序中使用包.应用程序在服务器上呈现,因此我编写了一些代码来确定使用和服务的语言IntlProvider.

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

export default {
  en: {
    message: '...some message',
    nested: {
      anotherMessage: '...another message',
    }
  }
  de: {
    // ...
  }
}
Run Code Online (Sandbox Code Playgroud)

我做的是这样的:

// 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>
Run Code Online (Sandbox Code Playgroud)

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

<FormattedMessage id="nested.anotherMessage" ... />
Run Code Online (Sandbox Code Playgroud)

但是message可以访问.

我犯错误的任何想法,或者我在整个概念中遗漏了什么?

ban*_*yan 13

由于React Intl v2不再支持嵌套消息对象,因此消息需要展平.

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)}>
Run Code Online (Sandbox Code Playgroud)

裁判:

  • 感谢那。我们决定使用“I18next”,因为这似乎是一个更灵活的库。 (2认同)

AHO*_*HOY 10

react-intl不再支持嵌套消息。如果您仍然想以这种方式组织您的消息,您可以使用该flat库提前更正您的消息结构。

import flatten from 'flat'

<IntlProvider locale={locale} messages={flatten(messagesForLocale)}>
Run Code Online (Sandbox Code Playgroud)

一位react-intl声称仅支持扁平消息结构的主要原因是:

简单性和灵活性是主要原因。使用平面对象,人们可以编写他们想要的任何消息 ID/键,并且不会用特殊的语义来解释它们。

在 GitHub 上查看问题支持嵌套消息对象 评论。