umijs / umi

A framework in react community ✨
https://umijs.org
MIT License
15.39k stars 2.65k forks source link

useIntl 在非组件的ts文件中无法使用 #4718

Closed soldier-shi closed 4 years ago

soldier-shi commented 4 years ago

What happens?

我尝试在封装的request.ts文件中使用国际化,如果使用 import { formatMessage } from 'umi'; 会报如下警告: devScripts.js:5035 Warning: Using this API will cause automatic refresh when switching languages, please use useIntl or injectIntl. 使用此 api 会造成切换语言的时候无法自动刷新,请使用 useIntl 或 injectIntl。

我尝试使用useIntl,报错如下: react-dom.development.js:14724 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app

我理解的大致意思就是在非组件的ts文件中无法使用,我想问的是,我在request.ts文件中如何使用国际化,因为这只是我封装的调接口的ts文件并不是react组件,某些提示框需要做国际化,应该怎么操作呢?

Mini Showcase Repository(REQUIRED)

Provide a mini GitHub repository which can reproduce the issue. Use yarn create @umijs/umi-app then upload to your GitHub

How To Reproduce

Steps to reproduce the behavior: 1. 2.

Expected behavior 1. 2.

Context

leftstick commented 4 years ago

提供你的可复现repo,或者参考中台助手

soldier-shi commented 4 years ago

https://github.com/MrShiss/umi-useIntl.git

leftstick commented 4 years ago

看了下你的用法,文档里已经介绍了faquseIntl 是 hooks,只能在react组件中用,这个没办法,umi建议你用她是因为体验更好。

所以,如果你执意要在非 react组件里使用,那就忽略警告,继续用 import { formatMessage } from 'umi' 好了,这个不是错。只是建议

soldier-shi commented 4 years ago

目前就是这样做的 想问问有没有别的api 感觉您的解答

wangjingithub commented 4 years ago

还有其他处理方案吗