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';
使用
<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>
<Link to='/second'>Home</Link> // to=字符串<Link to={{pathname: '/second',search: '?a=1',hash: '#123',state: { visible: true }}}>Home</Link> // to=Object
<NavLink activeClassName='selected' to='/home/123'>Second</NavLink>
扩展3------this.props
this.props上添加了history, location, match
扩展4------如何实现路由的切换
您可能遇到???
问题1:
<Router><Route exact path='/' component={Login} /><Route exact path='/second' component={Second} /></Router>
出现bug A <Router> may have only one child element 这说明Router中必须只有一个子元素,也就是说需要一个容器元素
问题2:
<Route component={App}><Route path="groups" components={Groups} /><Route path="users" components={Users}><Route path="users/:userId" component={Profile} /></Route></Route>
router4中 出现warning You should not use <Route component> and <Route children> in the same route
应该改为
<Route component={App}>
<Route path=
"groups"
components={Groups} />
<Route path=
"users"
components={Users}>
//<Route path="users/:userId" component={Profile} />
</Route>
</Route>
const Users = ({ match }) => (
<div>
<h2>Topics</h2>
<Route path={`${match.url}/:userId`} component={Profile}/>
</div>
)
ff