普通路由傳參的方式
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 是狀態(tài)管理的庫,router (react-router)是(唯一)控制頁面跳轉的庫。兩者都很美好,但是不美好的是兩者無法協(xié)同工作。換句話說,當路由變化以后,store 無法感知到。
redux是想把絕大多數應用程序的狀態(tài)都保存在單一的store里,而當前的路由狀態(tài)明顯是應用程序狀態(tài)很重要的一部分,應當是要保存在store中的。
目前是,如果直接使用react router,就意味著所有路由相關的信息脫離了Redux store的控制,假借組件接受router信息轉發(fā)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')
)
使用簡單直白的api syncHistoryWithStore來完成redux的綁定工作,我們只需要傳入react router中的history(前面提到的)以及redux中的store,就可以獲得一個增強后的history對象。 將這個history對象傳給react router中的Router組件作為props,就給應用提供了觀察路由變化并改變store的能力。 現在,只要您按下瀏覽器按鈕或在應用程序代碼中導航,導航就會首先通過Redux存儲區(qū)傳遞新位置,然后再傳遞到React Router以更新組件樹。如果您計時旅行,它還會將新狀態(tài)傳遞給React Router以再次更新組件樹。