1.react-router 和 react-router-dom的理解
4.0版本的路由已不需要路由配置,一切皆组件
react-router:提供了一些router的核心api,包括Router,Route,Switch等
react-router-dom:提供了BrowserRouter,HashRouter,Route,Link,NavLink
2.路由的安装
npm install react-router-dom --save 或 yarn add react-router-dom
3.react-router-dom的核心用法
HashRouter和BrowserRouter区别
http://localhost:3000/#/admin/home (HashRouter)
http://localhost:3000/admin/home (BrowserRouter)
import React from 'react';
import {HashRouter , Link , Route, Switch} from 'react-router-dom';
import Main from './Main';
import About from './About';
import Topic from './Topic';
export default class Home extends React.Component{
render(){
return (
<HashRouter> {/*跟路由,根路由下面不能直接放Route组件*/}
<div>
<ul>
<li>
<Link to='/'>home</Link>
</li>
<li>
<Link to='/about'>about</Link>
</li>
<li>
<Link to='/topic'>topic</Link>
</li>
</ul>
<hr />
{/* <Route exact path='/' component={Main}></Route> 精准匹配*/}
<Switch> {/*Switch只允许匹配一个,只有匹配到一个合适的就不会继续向下执行
,如果第一个路由/不加精准匹配,那么每次都会匹配main组件,然后停止加载下面的*/}
<Route exact={true} path='/' component={Main}></Route>
<Route path='/about' component={About}></Route>
<Route path='/topic' component={Topic}></Route>
</Switch>
</div>
</HashRouter>
);
}
}