React-Router v4.0上已經不推薦使用hashRouter,主推browserRouter,但是因為使用browserRouter需要服務端配合可能造成不便,有時還是需要用到hashRouter。下面是v4.0的React-Router中hashRouter以js方式跳轉的實現步驟。
- v4.0剝離了history,所以要操作history,需要安裝支持包:
npm install history --save
- 在要跳轉的地方對應的js文件中,引入createHashHistory并執行代碼,以跳轉到'/share'舉例:
import { createHashHistory } from 'history'
createHashHistory().push('/share')
- 大功告成。
在使用上述方法跳轉之前,需要確認已經定義Router,可參考下述代碼:
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>