React非组件UserService模块中后台定时器触发时如何实现浏览器跳转登录页
非React组件模块实现React路由跳转的两种解决方案
你可以根据项目的实际需求选以下任意一种方案实现:
方案1:使用原生浏览器API实现跳转(最简单通用)
不需要依赖任何React路由相关的能力,直接调用浏览器全局对象的方法即可实现,代码如下:
// Browser路由模式下使用 window.location.href = '/login' // 哈希路由模式下使用 window.location.hash = '#/login'
- 优点:零额外封装成本,所有JS模块都可以直接调用,跳转同时会自动清空当前页面内存中存储的过期用户状态、残留定时器等垃圾数据,避免后续业务逻辑出现异常
- 适用场景:对登录跳转没有无刷新体验要求的绝大多数业务场景,也是最推荐的常规实现方式
方案2:抽离公共history实例实现客户端无刷新跳转
如果需要走React客户端路由实现无刷新跳转,可以把react-router的history实例单独抽成公共模块,非组件模块直接导入调用即可。
实现步骤
- 安装history依赖(react-router自带该依赖,没有的话手动执行
npm install history安装即可) - 新建公共history文件
src/utils/history.js
// Browser路由模式 import { createBrowserHistory } from 'history' // 哈希路由模式请替换为 import { createHashHistory } from 'history' export const history = createBrowserHistory()
- 修改路由入口配置,使用自定义的history实例:
// react-router v6 写法 import { Router, Routes, Route } from 'react-router-dom' import { history } from './utils/history' import Login from './pages/Login' // 其他页面引入省略 function App() { return ( <Router location={history.location} navigator={history}> <Routes> <Route path="/login" element={<Login />} /> {/* 其他路由配置省略 */} </Routes> </Router> ) } // react-router v5 写法更简单,直接传入history即可 // <Router history={history}> // {/* 路由配置 */} // </Router>
- 在UserService模块中直接导入history实例调用跳转:
import { history } from '../utils/history' // 刷新token失败时执行跳转,replace方法可以避免用户按返回键回到过期页面 history.replace('/login')
- 优点:走客户端路由跳转,页面不会整页刷新,体验更流畅,可按需保留页面状态
- 适用场景:需要保留跳转前页面无状态缓存的业务场景
注意事项
跳转时优先使用replace而不是push,可以避免用户点击浏览器返回按钮回到已经失效的业务页面,符合登录跳转的常规交互逻辑。
内容的提问来源于stack exchange,提问作者Shawn de Wet
相关产品推荐
相关产品推荐

