1.從props取出並傳遞historycss
取 const { history } = this.props 用 <button onClick={ () => history.push('/') }>go back home</button>
2.withRouter, Linkhtml
withRouter:react
import { withRouter, Link } from 'dva/router' <button onClick={ () => history.push('/') }>go back home</button> export default withRouter(Counter);
Link:antd
import { withRouter, Link } from 'dva/router'; // 引入組件 <Link to='/'>home page</Link> 使用
3.routerReduxapp
import { routerRedux } from 'dva/router'; effects: { *asyncDecr({ payload }, { call, put }) { yield call(delay, 1000); yield put({type: 'decrement' }); yield put( routerRedux.push('/') ); // 路由跳轉 } },
使用query-string庫能夠將對象轉化爲url參數:async
effects: { *asyncDecr({ payload }, { call, put }) { yield call(delay, 1000); yield put({type: 'decrement' }); // yield put( routerRedux.push('/') ); // 路由跳轉 yield put( routerRedux.push({ pathname: '/', search: queryString.stringify({ from: 'product', to: 'home' }) }) ); // 路由跳轉 } },
效果:this
http://localhost:8000/?from=product&to=home
完整代碼:url
第一個是model文件products.js 第二個是routes下的UI文件ProductPage.jsspa
import { delay } from 'dva/saga'; import { routerRedux } from 'dva/router'; import queryString from 'query-string'; export default { namespace: 'products', state: { counter: 1, }, effects: { *asyncDecr({ payload }, { call, put }) { yield call(delay, 1000); yield put({type: 'decrement' }); // yield put( routerRedux.push('/') ); // 路由跳轉 yield put( routerRedux.push({ pathname: '/', search: queryString.stringify({ from: 'product', to: 'home' }) }) ); // 路由跳轉 } }, reducers: { 'increment'(state, action) { return { counter: state.counter + 1 } }, 'decrement'(state, action) { return { counter: state.counter - 1 } } } }
import React, { Component } from 'react'; import { connect } from 'dva'; import propTypes from 'prop-types'; import { Button } from 'antd'; import styles from './ProductPage.css'; import { increment, asyncDecr } from '../actions'; class ProductPage extends Component { constructor(props, context) { console.log(props); super(); } render() { const { products, dispatch, increment, asyncDecr } = this.props; return ( <div className={styles.wrapper}> <div className={styles.title}>結果 {products.counter}</div> <div> <p className={styles['p-wrapper']}> <Button type="primary" onClick={()=>dispatch({type:'products/increment',payload:1})}>incr</Button> <Button type="primary" onClick={()=>dispatch({type:'products/asyncDecr',payload:1})}>incr</Button> </p> <p className={styles['p-wrapper']}> <Button type="primary" onClick={()=>increment()}>increment</Button> <Button type="primary" onClick={()=>asyncDecr()}>asyncDecr</Button> </p> <Button type="primary">decr</Button> </div> </div> ); } } ProductPage.propTypes = { counter: propTypes.object }; const mapStateToProps = (state) => { return { products: state.products, }; }; export default connect(mapStateToProps, { increment, asyncDecr })(ProductPage);
這裏是最後一種路由跳轉方式,能夠輕鬆應對各類場景 https://www.tipsns.com/read/34.htmlcode