此篇文章未经过全部验证,仅供参考
转载自:https://www.cnblogs.com/juexin/p/9407391.html
1.从props取出并传递history
取 const { history } = this.props
用 <button onClick={ () => history.push('/') }>go back home</button>
2.withRouter, Link
withRouter:
import { withRouter, Link } from 'dva/router'
<button onClick={ () => history.push('/') }>go back home</button>
export default withRouter(Counter);
Link:
import { withRouter, Link } from 'dva/router'; // 引入组件
<Link to='/'>home page</Link> 使用
3.routerRedux
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参数:
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'
})
}) ); // 路由跳转
}
},
效果:
http://localhost:8000/?from=product&to=home
完整代码:
第一个是model文件products.js 第二个是routes下的UI文件ProductPage.js
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.html