使用 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);
这是官方推荐做法哦。但是这种方法用起来有点难受,比如我们想在redux
里面使用路由的时候,我们只能在组件把history
传递过去。。https://reacttraining.com/react-router/web/api/withRouter
// This gets around shouldComponentUpdate
withRouter(connect(...)(MyComponent))
// or
compose(
withRouter,
connect(...)
)(MyComponent)