使用UmiJS+qiankun插件搭建微前端应用(3)——父子应用通信

546 阅读1分钟

通信方式一:配合 useModel 使用(推荐)

需确保已安装 @umijs/plugin-model@umijs/preset-react

主应用透传数据方式一

如果你用的 MicroApp 组件模式消费微应用,那么数据传递的方式就跟普通的 react 组件通信是一样的,直接通过 props 传递即可:

function MyPage() {
  const [name, setName] = useState(null);

  return <MicroApp name={name} onNameChange={(newName) => setName(newName)} />;
}

主应用透传数据方式二

如果你用的 路由绑定式 消费微应用,那么你需要在 src/app.ts 里导出一个 useQiankunStateForSlave 函数,函数的返回值将作为 props 传递给微应用,如:

// src/app.ts
export function useQiankunStateForSlave() {
  const [masterState, setMasterState] = useState({});

  return {
    masterState,
    setMasterState,
  };
}

子应用获取数据方式一

子应用中会自动生成一个全局 model,可以在任意组件中获取主应用透传的 props 的值。

import { useModel } from 'umi';

function MyPage() {
  const masterProps = useModel('@@qiankunStateFromMaster');

  return <div>{JSON.stringify(masterProps)}</div>;
}

子应用获取数据方式二

通过高阶组件 connectMaster 来获取主应用透传的 props

import { connectMaster } from 'umi';

function MyPage(props) {
  return <div>{JSON.stringify(props)}</div>;
}

export default connectMaster(MyPage);

通信方式二:基于 props 传递

1.主应用中配置 apps 时以 props 将数据传递下去

// src/app.js

export const qiankun = fetch('/config').then((config) => {
  return {
    apps: [
      {
        name: 'app1',
        entry: '//localhost:2222',
        props: {
          onClick: (event) => console.log(event),
          name: 'xx',
          age: 1,
        },
      },
    ],
  };
});

2.子应用在生命周期钩子中获取 props 消费数据

// src/app.ts
export const qiankun = {
  // 应用加载之前
  async bootstrap(props) {
    console.log('app1 bootstrap', props);
  },
  // 应用 render 之前触发
  async mount(props) {
    console.log('app1 mount', props);
  },
  // 应用卸载之后触发
  async unmount(props) {
    console.log('app1 unmount', props);
  },
};