14.1 识别是否运行于发状态运行
下面是app.tsx的第一行代码,它展示了判断当前是否运行于开发状态的方法:
const isDev = process.env.NODE_ENV === 'development';
14.2 应用初始化及全局共享的数据
接下来一个比较重要的部分是getInitialState函数(我们给自动生成的代码加上了注释):
/*** @see https://umijs.org/zh-CN/plugins/plugin-initial-state* */export async function getInitialState(): Promise<{settings?: Partial<LayoutSettings>;currentUser?: API.CurrentUser;fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;//如果要返回更多的内容,可以补充在这里,最好不要定义成any,以增加可维护性}> {const fetchUserInfo = async () => {try {//queryCurrentUser的默认逻辑是直接向后端请求用户数据,//由后端判断当前用户的登录状态//可以改成前端先根据Token或Cookie判断是否需要登录const currentUser = await queryCurrentUser();return currentUser;} catch (error) {//这里出现异常一般是没有登录或者因超时需要重新登录history.push(loginPath);}return undefined;};// 如果不是登录页面,那么额外返回当前用户的信息if (history.location.pathname !== loginPath) {const currentUser = await fetchUserInfo();return {fetchUserInfo,currentUser,settings: {},};}//如果是登录页面,那么就只需要返回下面两项return {fetchUserInfo,settings: {},};}
这个getInitialState函数会在整个应用系统最开始被自动调用执行,它的返回值会成为全局共享的数据。Layout 插件、Access 插件以及用户都可以通过 useModel('@@initialState')直接获取到这份数据。如果想要重新执行 getInitialState 方法并获取新数据,或者手动设置 initialState 的值,也需要用useModel来实现,具体见官方文档。
脚手架初始化的时候getInitialState中完成的工作是获取当前用户信息,返回获取用户的函数、当前用户信息以及布局的设置LayoutSettings(详见代码中的注释)。实际与具体应用相关的初始化操作和全局共享数据都应该在这个函数中执行并返回。
更详细的说明参见https://umijs.org/zh-CN/plugins/plugin-initial-state
14.3 全局异常处理程序
app.tsx的第二个重要部分是全局异常处理程序。这部分的细节已经在上一章讨论过,这里不再赘述。
14.4 页面布局的运行时配置
app.tsx的第三个重要部分是页面布局的运行时配置(Rung-Time Page Layout Configuration),它通过export const layout = ({}) 来完成。
// ProLayout 支持的api https://procomponents.ant.design/components/layout// 同时可以参考UmiJS的文档 https://umijs.org/zh-CN/plugins/plugin-layoutexport const layout: RunTimeLayoutConfig = ({ initialState }) => {return {//在src/components/RightContent中实现rightContentRender: () => <RightContent />,disableContentMargin: false,//默认用当前用户的名字做水印waterMarkProps: {content: initialState?.currentUser?.name,},//在src/components/Footer中实现footerRender: () => <Footer />,onPageChange: () => {const { location } = history;// 如果没有登录,重定向到 loginif (!initialState?.currentUser && location.pathname !== loginPath) {history.push(loginPath);}},//在以开发状态运行的时候,在左侧最下显示两个和文档有关的链接//关于Open API的链接应该在第0章的时候被删除links: isDev? [<Link to="/~docs"><BookOutlined /><span>业务组件文档</span></Link>,]: [],menuHeaderRender: undefined,// 自定义 403 页面// unAccessible: <div>unAccessible</div>,...initialState?.settings,};};
此外,主题等与dom无关的配置都可以在文件config/config.ts 中配置。
更详细的内容参见下面两个链接
- @umijs/plugin-layout https://umijs.org/zh-CN/plugins/plugin-layout
- ProLayout高级布局 https://procomponents.ant.design/components/layout
更详细的内容见https://umijs.org/zh-CN/plugins/plugin-request
版权说明:本文由北京朗思云网科技股份有限公司原创,向互联网开放全部内容但保留所有权力。
