react-router v4 使用 history 控制路由跳轉

問題

當咱們使用react-router v3的時候,咱們想跳轉路由,咱們通常這樣處理

咱們從react-router導出browserHistory。 
咱們使用browserHistory.push()等等方法操做路由跳轉。 
相似下面這樣javascript

import browserHistory from 'react-router';

export function addProduct(props) {
  return dispatch =>
    axios.post(`xxx`, props, config)
      .then(response => {
        browserHistory.push('/cart'); //這裏
      });
}

 

問題來了,在react-router v4中,不提供browserHistory等的導出~~

那怎麼辦?我如何控制路由跳轉呢???java

解決方法

  • 使用 withRouter

withRouter高階組件,提供了history讓你使用~react

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傳遞過去。。ios

就像問題章節的代碼那種場景使用,咱們就必須從組件中傳一個history參數過去。。。redux

  • 使用 Context

react-router v4 在 Router 組件中經過Contex暴露了一個router對象~axios

在子組件中使用Context,咱們能夠得到router對象,以下面例子~react-router

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不推薦使用contex哦。在將來版本中有可能被拋棄哦。dom

  • hack

其實分析問題所在,就是v3中把咱們傳遞給Router組件的history又暴露出來,讓咱們調用了ide

而react-router v4 的組件BrowserRouter本身建立了history, 
而且不暴露出來,不讓咱們引用了。尷尬~post

咱們能夠不使用推薦的BrowserRouter,依舊使用Router組件。咱們本身建立history,其餘地方調用本身建立的history。看代碼~

下面是我目前所使用的辦法

咱們本身建立一個history

 // src/history.js


import createHistory from 'history/createBrowserHistory';

export default createHistory(); 

 

新的版本須要這樣引入

import { createHashHistory,createBrowserHistory } from 'history'; // 是hash路由 history路由 本身根據需求來定

  

ts引入

import * as createHistory from "history";
export default createHistory.createBrowserHistory();

  

 

 

 咱們使用Router組件

// 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`, props, config)
      .then(response => {
        history.push('/cart'); //這裏
      });
}

 

this.props.history.push("/two")

  

react-router v4推薦使用BrowserRouter組件,而在第三個解決方案中,咱們拋棄了這個組件,又回退使用了Router組件。

我目前也沒有更好的辦法了

相關文章
相關標籤/搜索