irpas技术客

关于UMI中 useModel的使用(踩坑记录)_独孤九溅

未知 2470

最近用React + UMI +qiankun的框架撸了一个后台管理系统,主应用使用的qiankun做的微前端,子运用使用的是UMI搭建的React 项目,涉及到主应用与子运用的通信问题。 1.主应用用的qiankun中的registerMicroApps进行的传值,代码如下:

registerMicroApps([ { name: 'react app', // app name registered entry: '//localhost:8080', container: '#yourContainer', activeRule: '/yourActiveRule', props:{ userId:'xxx' } },

2.子应用根据UMI提供的API:

import { useModel } from 'umi'; function MyPage() { const masterProps = useModel('@@qiankunStateFromMaster'); return <div>{JSON.stringify(masterProps)}</div>; }

所以按照官网的API的写法,我一开始是在项目中这样获取并赋值的

import { useModel } from 'umi' const College = () => { const [userId, setUserId] = useState<React.ReactNode>(false) const masterProps = useModel('@@qiankunStateFromMaster') if (masterProps && masterProps.userId { setUserId(masterProps.userId) } }

部署子应用后,一直报错

经过分析发现,原来是不能这么写,赋值的时候得放到hooks钩子函数中:

import { useEffect } from 'react' import { useModel } from 'umi' const College = () => { const [userId, setUserId] = useState<React.ReactNode>(false) const masterProps = useModel('@@qiankunStateFromMaster') useEffect(() => { if (masterProps && masterProps.userId { setUserId(masterProps.userId) } },[]) }


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #关于UMI中 #useModel的使用踩坑记录 #最近用React #umi