React-intl for non components

后端 未结 5 2193
醉酒成梦
醉酒成梦 2021-02-05 17:14

Currently I have the following code to expose react-intl to non-components, but it throws an error for intl as undefined.

I have created a separate component as \'Curren

5条回答
  •  别跟我提以往
    2021-02-05 17:14

    There's a new way to do it pretty easily with createIntl, it returns an object that you can use outside React components. Here's an example from the documentation.

    import {createIntl, createIntlCache, RawIntlProvider} from 'react-intl'
    
    // This is optional but highly recommended
    // since it prevents memory leak
    const cache = createIntlCache()
    
    const intl = createIntl({
      locale: 'fr-FR',
      messages: {}
    }, cache)
    
    // Call imperatively
    intl.formatNumber(20)
    
    // Pass it to IntlProvider
    {foo}
    

    I personally store the intl object in Redux store so I can access it everywhere in my app.

提交回复
热议问题