React Router 6.x中使用BrowserRouter时如何访问history对象?
在React Router v6.3.0的中获取history对象的方法
React Router v6 中,<BrowserRouter>默认会内部创建history实例,无法直接从外部获取。要拿到history对象并使用其length属性,有两种实用方案:
方案一:自定义history实例并传入
这是最直接的方式,步骤如下:
- 安装
history包(v6需要单独依赖该包):
npm install history@5 # 或 yarn add history@5
- 创建独立的history实例文件:
// src/history.js import { createBrowserHistory } from 'history'; export const history = createBrowserHistory();
- 替换
<BrowserRouter>为<Router>并传入自定义history:
// src/App.jsx import { Router } from 'react-router-dom'; import { history } from './history'; import YourRouteComponents from './YourRoutes'; function App() { return ( <Router history={history}> <YourRouteComponents /> </Router> ); } export default App;
- 在任意组件中直接导入使用:
import { history } from './history'; function CheckHistoryComponent() { // 判断是否有之前访问的页面 const hasPreviousPages = history.length > 1; return ( <div> {hasPreviousPages && <button onClick={() => history.goBack()}>返回上一页</button>} </div> ); }
方案二:用v6内置钩子间接判断(无需直接获取history)
如果只是要判断是否能回退到之前的页面,不一定非要用history.length,可以结合useNavigate和useNavigationType来实现:
import { useNavigate, useNavigationType } from 'react-router-dom'; function CheckBackButton() { const navigate = useNavigate(); const navigationType = useNavigationType(); // 首次加载时navigationType为POP,结合window.history.length判断是否有历史记录 const hasPreviousPages = navigationType !== 'POP' || window.history.length > 1; return ( <div> {hasPreviousPages && <button onClick={() => navigate(-1)}>返回</button>} </div> ); }
注意:React Router v6官方更推荐使用useNavigate等内置钩子处理导航逻辑,直接操作history对象属于偏底层的用法,按需选择即可。
内容的提问来源于stack exchange,提问作者Marcin
相关产品推荐
相关产品推荐

