使用route 之前需要先安装 react-router-dom
yarn add react-router-dom -D
在src根目录下新建router.js文件
//router.js
import React,{ Component } from 'react' import {Route, BrowserRouter, Switch, HashRouter} from 'react-router-dom' import Earnings from './page/earnings/earnings' import Home from './page/home/home' import UserVip from './page/userVip/userVip' export default class Router extends Component { render(){ return ( // 建议使用 HashRouter <HashRouter> <Switch>
// exact 精准匹配 <Route path="/" exact component={ UserVip }></Route> <Route path="/earnings" component={ Earnings } /> <Route path="/home" component={ Home } />
<Route component={ 如果前面的路由都没有匹配上,在此处返回404页面 } /> </Switch> </HashRouter> ) } }
第二种写法
import {Route, BrowserRouter, Switch, HashRouter} from 'react-router-dom'
import Earnings from './page/earnings/earnings'
import Home from './page/home/home'
import UserVip from './page/userVip/userVip'
export default function Router() {
return (
<HashRouter>
<Switch>
<Route path="/" exact component={ UserVip }></Route>
<Route path="/earnings" component={ Earnings } />
<Route path="/home" component={ Home } />
<Route component={ 如果前面的路由都没有匹配上,在此处返回404页面 } />
</Switch>
</HashRouter>
)
}
使用 在index.js中引入router.js
import React from 'react'; import ReactDOM from 'react-dom'; import Router from './router' ReactDOM.render( <Router></Router> ,document.getElementById('root'));