react-intl - 访问嵌套消息 [英] react-intl - accessing nested messages

查看:226
本文介绍了react-intl - 访问嵌套消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use react-intl package inside an app. The app is rendered on the server so I wrote some code to determine which language to use and serve into IntlProvider.

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

Translations were provided in messages.js file and they look like this:

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 ):

Then when I use FormattedMessage component I can't access the nested message (anotherMessage) with code like this:

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

消息是可以访问的。

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

Any ideas where I made the mistake, or maybe I'm missing something in the whole concept?

推荐答案

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

Since React Intl v2 no longer supports nested messages objects, the messages need to be flatten.

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/issues/162#issuecomment-139683466

这篇关于react-intl - 访问嵌套消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆