在非组件下使用 history
当我们使用了 HashRouter
或者BrowerRouter
,我们需要知道以下几点
Router
+HashHistroy
=HashRouter
Router
+BrowerHistroy
=BrowerRouter
在 react-router-dom@5.3.0
中 本身就提供了Router
,并且还提供了 history
这个包,
解决步骤:
- 这里我是对路由方面也进行了一个更改
- 如果只是单纯想使用 history , 可以直接创建 history(步骤: 2)
,并导入进行调用
- 使用
Router
,不要使用HashRouter
或BrowerRouter
import {
// HashRouter as Router
Router,
Route,
Switch
} from 'react-router-dom'
- 新建一个文件,创建
history
,并导出
import { createBrowserHistory } from 'history'
const history = createBrowserHistory()
export default history
- 导入
history
, 在Router
标签上添加 history属性,属性值则是导入的history
import history from '@/history'
export default function App () {
return (
<div className="app">
// 向Router上添加history属性
<Router history={history}>
<Switch>
<Route path="/" exact component={Login} />
<Route path="/login" component={Login} />
<AuthRoute path="/home" component={Layout} />
<Route component={NotFount} />
{/* <Redirect from="/" to="/login" /> */}
</Switch>
</Router>
</div>
)
}
- 在非组件中 , 导入创建的
history
, 就可以调用 history的方法,例如,replace,push
在非组件环境下使用 dispatch
解决步骤:
- 你是否在就纠结,无法在 非组件情况下,无法使用
import {useDispatch} from 'react-redux'
,const dispatch = useDispatch()
, 无法使用dispatch - 我们只需要在非组件下,导入redux中的 store文件,也就是用于整合 reducers和action的 store对象导入, 就可以使用store来调用-
store.dispatch()
import store from '@/store'
store.dispatch()