React-Router v4.0 hashRouter使用js跳轉

React-Router v4.0上已經不推薦使用hashRouter,主推browserRouter,可是由於使用browserRouter須要服務端配合可能形成不便,有時仍是須要用到hashRouter。下面是v4.0的React-Router中hashRouter以js方式跳轉的實現步驟。javascript

  1. v4.0剝離了history,因此要操做history,須要安裝支持包:
npm install history --save 
  1. 在要跳轉的地方對應的js文件中,引入createHashHistory並執行代碼,以跳轉到'/share'舉例:
import { createHashHistory } from 'history' createHashHistory().push('/share') 
  1. 已經ok了。

在使用上述方法跳轉以前,須要確認已經定義Router,可參考下述代碼:java

import { HashRouter as Router, Route, Switch } from 'react-router-dom' ... <Router> <App> <Switch> <Route path='/index' component={顯示的組件1}> <Route path='/share' component={顯示的組件2}> ... </Switch> </App> </Router>
相關文章
相關標籤/搜索