react-intl - accessing nested messages

后端 未结 3 1012
夕颜
夕颜 2021-02-19 03:23

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

相关标签:
3条回答
  • 2021-02-19 03:37

    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

    0 讨论(0)
  • 2021-02-19 03:41

    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:

    • https://github.com/yahoo/react-intl/wiki/Upgrade-Guide#flatten-messages-object
    • https://github.com/yahoo/react-intl/issues/162#issuecomment-139683466
    0 讨论(0)
  • 2021-02-19 03:44

    react-intl does not support nested messages anymore. If you still want to organize your messages that way, you can use the flat library to correct your messages structure beforehand.

    import flatten from 'flat'
    
    <IntlProvider locale={locale} messages={flatten(messagesForLocale)}>
    

    https://github.com/hughsk/flat

    0 讨论(0)
提交回复
热议问题