react-router v4 手动控制路由跳转

手动控制路由跳转,其实就是使用history来控制路由跳转的。。。
react-router v3我没用过,所以就不做比较了

1. 使用 withRouter

引入withRouterimport { withRouter } from "react-router-dom"
然后用高阶组件withRouter把要导出的组件传入进去
最后使用this.props.history.push()把你需要跳转的路由push进去就好了
  • 例子

import React from "react";
import { withRouter } from "react-router-dom";
import { message, Popconfirm } from "antd";
import "../css/feedback.css";

class Logout extends React.Component {

  constructor(props) {
    super(props);
  }

  confirm = () => {
    this.props.history.push("/");
  };
    
  cancel = () => {
    message.error("Click on No");
  };

  render() {
    return (
      
    );
  }
}

export default withRouter(Logout);

2.使用context

这个方法不太推荐,因为官方也不推荐,可能在react未来的版本会被废除
重点在这三段中
import PropTypes from "prop-types";  
static contextTypes = {
    router: PropTypes.object
}
this.context.router.history.push("/");  //把你需要跳转的路由push进去
import React from "react";
import PropTypes from "prop-types";
import { message, Popconfirm } from "antd";
import "../css/feedback.css";

class Logout extends React.Component {
  
  static contextTypes = {
    router: PropTypes.object
  }

  constructor(props) {
    super(props);
  }

  confirm = () => {
    this.context.router.history.push("/");
  };
    
  cancel = () => {
    message.error("Click on No");
  };

  render() {
    return (
      
    );
  }
}

export default Logout;

3.自己创建history

这是我个人比较喜欢也比较推荐的用法
import createHistory from 'history/createBrowserHistory';

export default createHistory();

在其他页面我们就可以引入history,注意下路径

import history from './history';

const skip = () => {
    history.push("/"); 
}

你可能感兴趣的:(react-router v4 手动控制路由跳转)