《Umijs》一、目录结构与路由

一、目录结构

1. .env 环境变量

PORT=8888
COMPRESS=none

2. /src/.umi 临时目录

如入口文件、路由等会临时生成到此。在 dev 和 build 时会被删除并重新生成。

3. /src/layouts

约定式路由时的全局布局文件。

4. /src/app.ts

运行时配置文件,可扩展运行时能力,如修改路由、修改 render 方法等。

二、路由

Umi 属于单页应用,仅加载一次 html,其余所有跳转由浏览器端完成。

1. exact 严格匹配

type:boolean,default:false

export default defineConfig({
  routes: [
    { path: "/", component: "@/pages/index" },
    // 需要完全匹配
    { exact: true, path: "/layout", component: "@/layout/index" },
  ],
});

2. 配置子路由

export default {
  routes: [
    {
      path: "/",
      component: "@/layout/index",
      routes: [
        { path: "/admin", component: "@/pages/admin" },
        { path: "/user", component: "@/pages/user" },
      ],
    },
  ],
};

然后在 /src/layout/index 中通过 props.children 渲染子路由

export default (props) => {
  return <div>{props.children}</div>;
};

这样,访问 /admin/user 就会带上 layout 组件。

3. redirect 跳转

export default {
  routes: [
    { path: "/", redirect: "/user" },
    { path: "/user", component: "@/pages/user" },
  ],
};

4. wrappers

配置路由的高阶组件封装,如路由级别的权限校验。 type: string[]

路由配置

export default {
  routes: [
    { path: "/", component: "@/pages/index", wrappers: ["@/wrappers/auth"] },
    { path: "/login", component: "@/pages/login" },
  ],
};

权限校验组件

import React from "react";
import { history } from "umi";

const auth = (props: any) => {
  const random = Math.random();
  if (random > 0.5) {
    history.push("/login");
  }

  return <div>{props.children}</div>;
};

export default auth;

这样,访问 / 时,就会通过 auth 组件的权限校验,如果通过则渲染 src/pages/index,否则跳转至登录页。

5. 路由组件参数

路由组件可通过 props 获取到以下属性:

  • match,当前路由和 url match 后的对象,包含 paramspathurlisExact
  • location,应用当前处于哪个位置,包含 pathnamesearchquery等属性
  • history
  • route,路由配置,包含pathexactcomponentroutes

6. 传递参数给子路由 cloneElement

import React from "react";

export default (props: any) => {
  return React.Children.map(props.children, (child) => {
    return React.cloneElement(child, { foo: "bar" });
  });
};
文章作者: koral
文章链接: http://luokaiii.github.io/2020/04/07/读书笔记/《Umijs》官方文档/1.目录结构与路由/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自