背景: 需要在非组件环境跳转到指定页面, 言外之意也就是不能使用useHistory了.
react-router-dom中直接有Router这个包,但是这个Router 没有history属性.而有history属性的其他两个为HashRouter和BrowserRouter.这两个也不是凭空就有的history属性.如图
所以我们需要自己来封装一个包含history信息的utils来帮助我们实现.
安装react-router-dom时,默认会安装history包,我们可以通过这个包来自己创建history对象
为了能够在非组件环境下拿到路由信息,需要我们自定义 Router 的 history
// App.js部分代码
import { Router, Route, Switch, Redirect } from 'react-router-dom'
import { createBrowserHistory } from 'history'
export const history = createBrowserHistory()
function App () {
return (
<Router history={history}>
解决方案有二:
一、用window.location.href直接赋值(暴力解决)
有副作用,就是会导致页面刷新
二、封装一个history工具来拿到路由跳转信息,再传给需要该信息的组件
-
创建 utils/history.js 文件
<