React Router v6 如何获取history栈判断路由是否可前进
实现方法
你可以直接通过React Router提供的history实例属性拿到完整路由栈、判断是否可前进,不同版本实现方式略有差异:
React Router v5
直接使用useHistory Hook获取路由实例即可,不需要额外改造:
history.entries:完整的history栈数组,每一项对应栈里的路由记录history.index:当前激活路由在栈中的下标- 可前进判断逻辑:
history.index < history.entries.length - 1,结果为true时就代表栈中当前路由后面还有记录,可以执行前进操作
代码示例:
import { useHistory } from 'react-router-dom'; function PageA() { const history = useHistory(); const canGoForward = history.index < history.entries.length - 1; const handleGoForward = () => { if (canGoForward) history.goForward(); }; return ( <div> {/* 直接打印栈内容 */} <p>当前history栈:{JSON.stringify(history.entries.map(item => item.pathname))}</p> <button onClick={handleGoForward} disabled={!canGoForward}> 前进 </button> </div> ); }
把这个组件放到你原来的MemoryRouter子树里,渲染/a的时候就能拿到['/a', '/b']的栈内容,canGoForward会返回true,符合你的场景。
React Router v6
v6没有在公开API里直接向组件暴露完整的history实例,生产环境推荐提前自行创建memory history实例,再传入路由组件持有引用:
- 先安装和react-router版本匹配的
history依赖 - 提前初始化memory history,替换原来直接写在
MemoryRouter上的配置 - 用
HistoryRouter(部分版本为unstable_HistoryRouter)替代原来的MemoryRouter,传入创建好的history实例 - 组件内直接读取这个history实例的
entries、index属性做判断即可
代码示例:
import { createMemoryHistory } from 'history'; import { unstable_HistoryRouter as HistoryRouter, Routes, Route } from 'react-router-dom'; import PageA from './PageA'; import PageB from './PageB'; // 全局持有history实例,和你原来的配置保持一致 const memoryHistory = createMemoryHistory({ initialEntries: ['/a', '/b'], initialIndex: 0 }); function App() { return ( <HistoryRouter history={memoryHistory}> <Routes> <Route path="/a" element={<PageA />} /> <Route path="/b" element={<PageB />} /> </Routes> </HistoryRouter> ); }
PageA组件内的判断逻辑和v5一致,直接读取memoryHistory的属性即可:
function PageA() { const canGoForward = memoryHistory.index < memoryHistory.entries.length - 1; const handleGoForward = () => { if (canGoForward) memoryHistory.forward(); }; return ( <div> <p>当前history栈:{JSON.stringify(memoryHistory.entries.map(item => item.pathname))}</p> <button onClick={handleGoForward} disabled={!canGoForward}> 前进 </button> </div> ); }
注意:不推荐从v6的路由上下文中读取内部navigator属性拿history,这类内部API在小版本迭代中可能发生变更,会导致线上代码报错。
内容的提问来源于stack exchange,提问作者sdfsdf
相关产品推荐
相关产品推荐

