React-Router v4.0上已經(jīng)不推薦使用hashRouter,主推browserRouter衬廷,但是因?yàn)槭褂胋rowserRouter需要服務(wù)端配合可能造成不便摇予,有時(shí)還是需要用到hashRouter。下面是v4.0的React-Router中hashRouter以js方式跳轉(zhuǎn)的實(shí)現(xiàn)步驟吗跋。
- v4.0剝離了history侧戴,所以要操作history,需要安裝支持包:
npm install history --save
- 在要跳轉(zhuǎn)的地方對應(yīng)的js文件中跌宛,引入createHashHistory并執(zhí)行代碼酗宋,以跳轉(zhuǎn)到'/share'舉例:
import { createHashHistory } from 'history'
createHashHistory().push('/share')
- 大功告成。
在使用上述方法跳轉(zhuǎn)之前疆拘,需要確認(rèn)已經(jīng)定義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>