React-router
React-router提供了一些router的核心api,包括 Router, Route, Switch 等,但是它没有提供dom操作进行跳转的api。
React-router-dom
React-router-dom提供了 BrowserRouter, Route, Link 等api,我们可以通过dom的事件控制路由。例如点击一个按钮进行跳转,大多数情况下我们是这种情况,所以在开发过程中,我们更多是使用React-router-dom。
引入
import { BrowserRouter as Router, HashRouter, Route, Switch } from 'react-router-dom';
HashRouter不太推荐使用,路由:http://localhost:3000/#/,看起来比较怪
使用
<Router><Switch><Route exact path="/" component={Login} /><Route path="/login" component={Login} /></Switch></Router>
exact控制匹配到/路径时不会再继续向下匹配,path标识路由的路径,component表示路径对应显示的组件。
扩展***
扩展1-------全部匹配,渲染
<Router><div><Route path='/' component={Login} /><Route path='/second' component={Second} /></div></Router>
http://localhost:3000/second Login组件和Second组件都被渲染,而往往我们只想渲染Second组件
解决办法:
使用Switch,Switch常用于Router中作为容器组件,它使得路由变为唯一匹配,匹配到第一个路由不再往后匹配
<Router><Switch><Route exact path='/' component={Login} /><Route path='/second' component={Second} /><Route path='/second1' component={Home} /></Switch></Router>
此时http://localhost:3000/second只渲染Second组件
扩展2------
Link和NavLink的选择
<Link to='/second'>Home</Link> // to=字符串<Link to={{pathname: '/second',search: '?a=1',hash: '#123',state: { visible: true }}}>Home</Link> // to=Object
NavLink提供更多的Api,如前选中的路由设置类名、样式以及回调函数
<NavLink activeClassName='selected' to='/home/123'>Second</NavLink>
扩展3------this.props
this.props上添加了history, location, match
您可能遇到???
问题1:
<Router><Route exact path='/' component={Login} /><Route exact path='/second' component={Second} /></Router>
出现bug A <Router> may have only one child element 这说明Router中必须只有一个子元素,也就是说需要一个容器元素