一个路由就是一个通道,页面之间的跳转其实就是路由的切换,所以每个应用的路由配置是必须的,浅谈react中怎么配置路由
首先你要在src文件夹下新建一个router的文件下,在router文件下新建一个index.js(我用的是TS,所以是index.tsx)
然后在index.jsx里这样去配置
1 import React, { ReactNode, lazy } from "react"; 2 const Test = lazy(() => import("../pages/Test")) 3 const Detail = lazy(() => import("../pages/Detail")) 4 //Test 和 Detail分别对应你的组件 5 export interface IRoute { 6 exact?: boolean 7 path: string 8 title: string 9 icon?: ReactNode 10 component?: ReactNode 11 children?: IRoute[] 12 } 13 14 export const routes: IRoute[] = [ 15 { 16 path: "/test", 17 title: "测试一", 18 component: <Test /> 19 }, 20 { 21 path: "/detail", 22 title: "详情", 23 component: <Detail /> 24 } 25 ]
然后再在scr文件下新建一个components文件下,在此文件夹下新建一个View.jsx的文件,里面这样配置
1 import React, { Component, Suspense } from 'react' 2 import { HashRouter as Router, Switch, Route } from 'react-router-dom' 3 import { routes } from '../router' 4 export default class View extends Component { 5 render() { 6 return ( 7 <> 8 <Suspense fallback={<>loading ...</>}> 9 <Router> 10 {routes.map(r => (<Switch key={r.path}> 11 <Route path={r.path}> 12 {r.component} 13 </Route> 14 </Switch>))} 15 </Router> 16 </Suspense> 17 18 </> 19 ) 20 } 21 }
然后你就可以试着改变url地址栏来改变页面了,注意;hash模式下,你的url前必须加#/
用history来跳转页面时必须做好配置,部分代码如下:
1 import { Link, withRouter, RouteComponentProps } from 'react-router-dom'; 2 3 4 class Test extends Component{ 5 6 7 } 8 9 export default withRouter(Test)
这样才可以使用this.props.history.push等等api