umijs max React 的代码打包多份再运行react找不到问题

mf-dep____vendor.80125e40.js:263462 Warning: 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
    See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

Uncaught TypeError: Cannot read properties of null (reading ‘useContext’)

根因在某些复杂场景下,React 的代码被打包多份,再运行时产出了多个 React 实例。解法通过 Module Feratation 的 shared 配置来避免多实例的出现。 如果有其他依赖出现多实例的问题,可以通过类似的方式解决。

在config/config.ts文件里加mfsu的配置

mfsu: {
  shared: {
    react: {
      singleton: true,
    },
  },
},

Umi Max 国际化使用

ReactElement内使用

import { FormattedMessage } from '@umijs/max';
<FormattedMessage id="project.tunnel.label" />

函数内使用

import { useIntl } from '@umijs/max';
const AppLayout = ({ children, version }: any) => {
  const intl = useIntl();
  const msg = intl.formatMessage({ id: 'project.menu.draw.index' });
}

外部文件使用

import { getIntl, getLocale } from '@umijs/max';
const intl = getIntl(getLocale());
message.error(intl.formatMessage({ id: error.response.data.message}));

injectIntl还没遇到需要的地方,暂时不了解用法。