react-router-dom

2019-05-13  本文已影响0人  Clover园

https://www.jianshu.com/p/8954e9fb0c7e

npm install react-router-dom --save-dev //这里可以使用cnpm代替npm命令

一个基本的location对象

{pathname:'/',search:'',hash:'',key:'123',state:{}}

history={hashHistory}

  <BrowserRouter history={hashHistory}>
      <Switch>
            <Route exact path="/" component={Home}/>
            <Route exact path="/detail" component={Detail}/>
        </Switch>
    </BrowserRouter>

//通过this.props.history.push('路由url')这个函数跳转,不传参数的话直接写路由路径如 '/detail';
//http://localhost:3000/#/admin/buttons       //HashRouter是根路由, 4.0已经没有了
//http://localhost:3000/admin/buttons       //BrowserRouter,主要用于前后端分离的时候使用
//exact={true}精确匹配

url传参

//1.通过push函数隐式传参。获取传过来参数:this.props.history.location.state
<button onClick={() => this.props.history.push({
        pathname: '/detail',
        state: {
           id: 3
        }
})}>通过函数跳转</button>

//2.link传参
<Link to={{pathname:'/three/7'}}>Three #7</Link>

//定义
<Route path="/three/:number" />

//获取参数
this.props.match.params.number

其他

//react-router-dom提供了replace。在可能会出现死循环的地方使用replace来跳转:
this.props.history.replace('/detail');

//场景中需要返回上级页面的时候使用:
this.props.history.goBack();
上一篇 下一篇

猜你喜欢

热点阅读