umi 框架入门

7,141 阅读2分钟

路由系统

1.路由注册

1.约定式路由

通过文件路径来渲染

2.配置式路由

1.umi3 配置方式

在配置文件routes进行配置,格式为数组

export default {
  routes: [
    { exact: true, path: '/', component: 'index' },
    { exact: true, path: '/user', component: 'user' },
  ],
}

参数:

path:

路由路径

component:

路由对应的文件路径,可以是绝对路径也可以是相对路径,如果是绝对路径,会从src/pages开始找起,如果指向src目录的文件,可以用@,也可以用../,建议使用@短路径

exact:

路由匹配方式,开启严格匹配

routes:

配置路由的子路由

export default {
  routes: [
    { path: '/login', component: 'login' },
    {
      path: '/',
      component: '@/layouts/index',
      routes: [
        { path: '/list', component: 'list' },
        { path: '/admin', component: 'admin' },
      ],
    }, 
  ],
}

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

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

redirect:

配置路由跳转(路由重定向)

export default {
  routes: [
    { exact: true, path: '/', redirect: '/list' },
    { exact: true, path: '/list', component: 'list' },
  ],
}

访问 / 会跳转到/list,并渲染src/pges/list文件

wrappers:

配置路由的高阶组件(权限效验等其他需要逻辑操作的路由)

官方示例:

export default {
  routes: [
    { path: '/user', component: 'user',
      wrappers: [
        '@/wrappers/auth',
      ],
    },
    { path: '/login', component: 'login' },
  ]
}

然后在src/wrappers/auth 中,

export default (props) => {
  const { isLogin } = useAuth();
  if (isLogin) {
    return <div>{ props.children }</div>;
  } else {
    redirectTo('/login');
  }
}

访问/user时,就通过useAuth做权限效验,效验通过渲染src/pages/user,效验不通过跳转至指定路由(登录或报错路由页面)

测试过程中:useAuth文件报错redirectTo, redirectTo 如何获取?

改进版:

export default (props) => {
  console.log(props)
  let isLogin  =false;
  if (isLogin) {
    return <div>{ props.children }</div>;
  } else {
    props.history.push('/app');          // 权限不匹配跳至指定的页面
    return null
  }
}

title:

配置路由的标题

页面跳转

import { history } from 'umi';

// 跳转到指定路由
history.push('/list');

// 带参数跳转到指定路由
history.push('/list?a=b');
history.push({
  pathname: '/list',
  query: {
    a: 'b',
  },
});

// 跳转到上一个路由
history.goBack();

子组件获取参数:
this.props.location.query

Link组件,只能用于内部组件跳转

import { Link } from 'umi';

export default () => (
  <div>
    <Link to="/users">Users Page</Link>
    // link组件传参
    <Link to={`/user?documentQuery=23234234`}>路由传参</Link>
  </div>
);

子组件获取参数
this.props.location.query.documentQuery

路由参数获取

路由组件通过props获取路由参数:

.match, 当前路由和url match 后的对象,包含parms、path、url 和isExact

. location, 表示应用当前的出口,包含pathName、search、query属性

.hisory, 同histoty接口

.route, 当前路由配置,包含 path、exact、component、routes等

路由传参方式

通过cloneElement传参

import React from 'react';

export default function Layout(props) {
  return React.Children.map(props.children, child => {
    return React.cloneElement(child, { foo: 'bar' });
  });
}