react-intl - accessing nested messages

后端 未结 3 1018
夕颜
夕颜 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: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
    
    

    refs:

    • https://github.com/yahoo/react-intl/wiki/Upgrade-Guide#flatten-messages-object
    • https://github.com/yahoo/react-intl/issues/162#issuecomment-139683466

提交回复
热议问题