react-router react路由层

React-router

React-router提供了一些router的核心api,包括 Router, Route, Switch 等,但是它没有提供dom操作进行跳转的api。

React-router-dom

React-router-dom提供了 BrowserRouter,  RouteLink 等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

扩展4------如何实现路由的切换

this.props.history .replace('/home');  //  页面不会刷新

您可能遇到???

问题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

转载于:https://www.cnblogs.com/shiyujian/p/9862330.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值