非组件环境下拿到路由信息(React)

414 阅读1分钟

用location.href直接赋值会导致页面刷新。

如何在非组件内跳转?

背景

react-router-dom中直接有Router这个包,但是它Router 没有history属性

有如下公式:

Router + HashHistroy = HashRouter

Router + BrowerHistroy = BrowerRouter

github:参考

安装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}>

说明:为了能够在非组件环境下拿到路由信息,需要我们自定义 Router 的 history

步骤

  1. 创建 utils/history.js 文件
  2. 在该文件中,创建一个 hisotry 对象并导出
  3. 在 App.js 中导入 history 对象,并设置为 Router 的 history

核心代码

utils/history.js 中:

 // 自定义history对象
 import { createBrowserHistory } from 'history'
 
 const history = createBrowserHistory()
 
 export default history

App.js 中:

 // 注意:此处,需要导入 Router 组件
 import { Router } from 'react-router-dom'
 import history from '@/utils/history'
 
 function App() {
   return (
     <Router history={history}></Router>
   )
 }