基于umi 3.x对于react路由使用的总结(持续更新中。。。)

1,212 阅读1分钟

【前言】

umi对react-router-dom进行了很好的封装,这里对路由的使用进行个总结

【本文目录】

  1. 编程式导航

编程式导航

先看下项目目录(省略了node_modules.umi文件夹):

.
├── .editorconfig
├── .gitignore
├── .prettierignore
├── .prettierrc
├── .umirc.ts
├── README.md
├── mock
│   └── .gitkeep
├── package.json
├── src
│   └── pages
│       ├── about
│       │   ├── index.less
│       │   └── index.tsx
│       ├── index.less
│       ├── index.tsx
│       ├── list1
│       │   ├── index.less
│       │   └── index.tsx
│       └── list2
│           ├── index.less
│           └── index.tsx
├── tsconfig.json
├── typings.d.ts
└── yarn.lock

page目录下index.tsx的内容:

import React from 'react';
import styles from './index.less';
import { history } from 'umi'

const page = () => {
  const push: ( path: string) => void = (path) => {
    history.push({
      pathname: path,
      query: {//传递参数
        a: 'b',
      },
    })
  }
  return (
    <div>

      <h1 className={styles.title} onClick={ () => { push('/about') }}>about index</h1>
      <h1 className={styles.title} onClick={ () => { push('/about/list1') }}>list1 index</h1>
      <h1 className={styles.title} onClick={ () => { push('/about/list2') }}>list2 index</h1>
    </div>
  );
}

export default page

about/index的内容:

import React, { FC }from 'react';
import { history, Route, Location } from 'umi'
import list1 from '../list1/index'
import list2 from '../list2/index'

interface IBaseObject{
  key?: any
}
interface IUmiLocation {
    query: IBaseObject
}
interface HomeProps {
  a: string,
  children: FC,
  location: Location & IUmiLocation
}
const page: FC<HomeProps> = (props: HomeProps) => {
  const goBack = () => {
    history.goBack();
  }
  console.log('children', props.location.query)//获取参数
  return (
    <div>
      <h1>this is about page</h1>
      <h2 onClick={ () => goBack() }>go back</h2>
      <div>
        {props.children}
      </div>
      {/* 也可以用下面的方式显示子路由 */}
      {/* <div>
        <Route path= '/about/list1' component={list1}></Route>
      </div>

      <div>
        <Route path= '/about/list2' component={list2}></Route>
      </div> */}
    </div>
  );
}

export default page

这样一来就实现了编程时导航了。

参看文献

reactrouter.com/web/guides/…

umijs.org/zh-CN/docs/…