React-Router 4.0版本以上
第一种:this.props.history.push(path)
React-Router 4.0对路由进行了改进,router属性改为了history属性,使用方法还是和3.0差不多,任何需要跳转的地方使用this.props.history.push('/path')
就可以进行跳转了
参数的获取
使用this.props.match.params.xxx
可以获取到当前路由的参数
第二种:this.context.router.push(path)
文件要额外添加一些内容
- class Example extends React.Component {
- constructor(props, context) {
- super(props, context);
- this.context.router; // it works
- }
- ...
- this.context.router.push(path);
- }
- Example.contextTypes = {
- router: React.PropTypes.object
- };
- class index extends React.Component {
- render() {
- return (
- <div>
- home page
- </div>
- );
- }
- componentWillMount() {
- if (noLogin == 1) {
- this.context.router.push({ pathname : '/', state : { msg : 'you have logined and will redirect to your page'}});
- } else if (noLogin == 0) {
- this.context.router.push({ pathname : '/login', state : { msg : 'you do not login yet, please login' }});
- }
- }
- }
- class LoginPage extends React.Component {
- constructor(props, context) {
- super(props, context);
- }
- render() {
- return (
- <div>
- {this.props.location.state}
- </div>
- );
- }
- }