react-router v4 使用 history 控制路由跳转
原文地址: https://github.com/brickspert... (如果你觉得对你有帮助,可以去github上点个star哦。) github上会更新,这里不更新 问题当我们使用
类似下面这样 import browserHistory from 'react-router'; export function addProduct(props) { return dispatch => axios.post(`xxx`,props,config) .then(response => { browserHistory.push('/cart'); //这里 }); } but!! 问题来了,在 那怎么办?我如何控制路由跳转呢??? 解决方法1. 使用 withRouter
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); 这是官方推荐做法哦。但是这种方法用起来有点难受,比如我们想在 就像问题章节的代码那种场景使用,我们就必须从组件中传一个 2. 使用 Context
在子组件中使用 import React from "react"; import PropTypes from "prop-types"; class MyComponent extends React.Component { static contextTypes = { router: PropTypes.object } constructor(props,context) { super(props,context); } ... myFunction() { this.context.router.history.push("/some/Path"); } ... } 当然,这种方法慎用~尽量不用。因为react不推荐使用 3. hack其实分析问题所在,就是 而 我们可以不使用推荐的
// src/history.js import createHistory from 'history/createBrowserHistory'; export default createHistory();
// src/index.js import { Router,Link,Route } from 'react-router-dom'; import history from './history'; ReactDOM.render( <Provider store={store}> <Router history={history}> ... </Router> </Provider>,document.getElementById('root'),);
import history from './history'; export function addProduct(props) { return dispatch => axios.post(`xxx`,config) .then(response => { history.push('/cart'); //这里 }); } 4. 我非要用
|