问题
当我们使用react-router v3
的时候,我们想跳转路由,我们一般这样处理
- 我们从
react-router
导出browserHistory
。 - 我们使用
browserHistory.push()
等等方法操作路由跳转。
类似下面这样
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
等的导出~~
那怎么办?我如何控制路由跳转呢???
解决方法
使用 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
传递过去。。
就像问题章节的代码那种场景使用,我们就必须从组件中传一个history
参数过去。。。