当咱们使用react-router v3
的时候,咱们想跳转路由,咱们通常这样处理react
react-router
导出browserHistory
。browserHistory.push()
等等方法操做路由跳转。相似下面这样ios
import browserHistory from 'react-router'; export function addProduct(props) { return dispatch => axios.post(`xxx`, props, config) .then(response => { browserHistory.push('/cart'); //这里 }); }
but!! 问题来了,在react-router v4
中,不提供browserHistory
等的导出~~redux
那怎么办?我如何控制路由跳转呢???axios
withRouter
高阶组件,提供了history
让你使用~react-router
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
传递过去。。dom
就像问题章节的代码那种场景使用,咱们就必须从组件中传一个history
参数过去。。。post