React Router 4.0后使用js代码控制路由跳转的方法

现在需要用react实现一个需求,每当页面请求链接/跳转时需要向服务器验证当前登录态,请求链接的函数封装在一个叫request.js的工具里(非组件),当返回鉴权失败时需要跳转到错误页面,要求不使用window.location.href方法,因为需要传递参数但不得暴露,4.0版本前有hashHistory可以实现类似的功能,那么4.0版本之后要怎么办呢?

阅读 1.4k
1 个回答

使用 withRouter
withRouter高阶组件,提供了history让你使用~

import React from "react";
import {withRouter} from "react-router-dom";

class MyComponent extends React.Component {
...
myFunction() {
this.props.history.push("/some/Path");
}
...
}
export default withRouter(MyComponent);

这样就好了

推荐问题