在组件中如何获取history、match、location路由API?
路由组件可以直接在props上获取,非路由组件需要用withRouter高级组件包裹后在props上获取
在store或非组件的js中如何获取history路由API?
//手动引入
import {createBrowserHistory} from 'history'
const history = createBrowserHistory()
history.push('/test')
但是这种方法只会改变路由,页面并没有随着路由变化。
解决方法:
<BrowserRouter>
...
</BrowserRouter>
//修改成下面的
<Router history={history}>
...
</Router>
还有一种页面不更新的场景:
<Switch>
<Route path='/' component={Test} />
<Route path='/test2' component={Test2} />
<Route path='/test3' component={Test3} />
<Route path='/test4' component={Test4} />
</Switch>
发现路由不管如何变化始终都是显示的Test组件,
原因:
Switch会匹配第一个路由符合的组件,例如当前路由为’/test2‘,会匹配’/‘和’/test2’。所以一直都是显示Test组件。
解决方法:
将根路由放在最下面或者增加exact属性。
其他页面不刷新的情况可能是多个高阶组件包裹组件时引起的,将withRouter放在最外层包裹