react-intl - accessing nested messages

对着背影说爱祢 提交于 2019-12-04 03:56:02
banyan

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

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:

import flatten from 'flat'

<IntlProvider locale={locale} messages={flatten(messagesForLocale)}>

Yes, customization using flattenMessages is the best way I found.

Here is the video demo for your reference.

https://egghead.io/lessons/react-convert-a-hard-coded-string-using-react-intl-formattedmessage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!