react路由传参、路由跳转方式

普通路由传参的方式
search

// 传
this.props.history.push({
  pathname: path,
  search: 'name=huang&age=22'
})
// 取
this.props.location.search

params

// 传
/todo/:id
// 传
/todo/140504
// 取
this.props.match.params.id

通过state

// 传
this.props.history.push({
  pathname,
  state: {
    name: 'huang',
    age: 22
  }
})
// 取
this.props.location.state

dva路由跳转
.从props取出并传递history

const { history } = this.props
用 <button onClick={ () => history.push('/') }>go back home</button>

.withRouter, Link
1.withRouter:

<pre>import { withRouter, Link } from 'dva/router'
<button onClick={ () => history.push('/') }>go back home</button> export default withRouter(Counter);</pre>

2.Link:

import { withRouter, Link } from 'dva/router'; // 引入组件 

<Link to='/'>home page</Link> // 使用

.routerRedux

import { routerRedux } from 'dva/router';

effects: { 
*asyncDecr({ payload }, { call, put }) { 
      yield call(delay, 1000); yield put({type: 'decrement' }); 
      yield put( routerRedux.push('/') ); // 路由跳转
   }
},

routerRedux不仅可以在model里面使用,也可以在页面上使用,类似于:

// 页面上导入
import { connect } from 'dva';
import { routerRedux } from 'dva/router';

/**
   * 路由跳转
   * @param {object} record - 列表行数据
   */
  @Bind()
  handleToDetail() {
    const { dispatch } = this.props;
    dispatch(
      routerRedux.push({
        pathname,
        search: ‘’, // 查询参数 类似于 普通路由search传参
      })
    );
  }

跳转过去的页面获取参数的方式为this.props.location。url的信息都在location里面

对于routerRedux来说是dva在redux、react-router-redux封装的库。这里不得不提react-router-redux出现的原因了。

redux 是状态管理的库,router (react-router)是(唯一)控制页面跳转的库。两者都很美好,但是不美好的是两者无法协同工作。换句话说,当路由变化以后,store 无法感知到。

redux是想把绝大多数应用程序的状态都保存在单一的store里,而当前的路由状态明显是应用程序状态很重要的一部分,应当是要保存在store中的。

目前是,如果直接使用react router,就意味着所有路由相关的信息脱离了Redux store的控制,假借组件接受router信息转发dispatch的方法属于反模式,违背了redux的设计思想,也给我们应用程序带来了更多的不确定性。

所以react-router-redux应运而生。
react-router-redux使用案例:

import React from 'react'
import ReactDOM from 'react-dom'
import { createStore, combineReducers } from 'redux'
import { Provider } from 'react-redux'
import { Router, Route, browserHistory } from 'react-router'
import { syncHistoryWithStore, routerReducer } from 'react-router-redux'

import reducers from '<project-path>/reducers'

const store = createStore(
  combineReducers({
    ...reducers,
    routing: routerReducer
  })
)

const history = syncHistoryWithStore(browserHistory, store)

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <Route path="/" component={App} />
    </Router>
  </Provider>,
  document.getElementById(‘app')
)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱技术的大仙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值