如何实现react路由监听
实现 React 路由监听的方法
使用 useEffect 监听路由变化
在函数组件中,可以通过 useEffect 结合 useLocation 监听路由变化。useLocation 会返回当前的 location 对象,每当路由变化时,location 会更新,从而触发 useEffect。
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
function MyComponent() {
const location = useLocation();
useEffect(() => {
console.log('路由变化:', location.pathname);
// 执行其他逻辑
}, [location]);
}
使用 history.listen 监听路由变化
通过 history 对象的 listen 方法,可以手动监听路由变化。适用于类组件或需要全局监听路由的场景。

import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
history.listen((location, action) => {
console.log('路由变化:', location.pathname);
console.log('路由动作:', action); // PUSH, REPLACE, POP
});
// 在路由配置中使用自定义 history
import { Router } from 'react-router-dom';
function App() {
return <Router history={history}>{/* 路由配置 */}</Router>;
}
使用 useNavigate 监听导航动作
useNavigate 返回的 navigate 函数可以用于编程式导航,同时可以通过拦截导航动作实现监听。

import { useNavigate } from 'react-router-dom';
function MyComponent() {
const navigate = useNavigate();
const handleNavigation = (path) => {
console.log('即将导航到:', path);
navigate(path);
};
return <button onClick={() => handleNavigation('/new-path')}>导航</button>;
}
使用路由守卫(高阶组件)
通过高阶组件拦截路由变化,实现类似路由守卫的功能,适用于权限控制或全局路由监听。
import { useLocation, useNavigate } from 'react-router-dom';
function withRouterListener(WrappedComponent) {
return function (props) {
const location = useLocation();
const navigate = useNavigate();
useEffect(() => {
console.log('路由变化:', location.pathname);
// 检查权限或其他逻辑
if (!hasPermission(location.pathname)) {
navigate('/login');
}
}, [location]);
return <WrappedComponent {...props} />;
};
}
// 使用高阶组件
const ProtectedComponent = withRouterListener(MyComponent);
监听路由参数变化
如果只需要监听路由参数的变化,可以通过 useParams 结合 useEffect 实现。
import { useParams } from 'react-router-dom';
function UserProfile() {
const { userId } = useParams();
useEffect(() => {
console.log('用户ID变化:', userId);
// 根据 userId 获取用户数据
}, [userId]);
}
注意事项
- 在
useEffect中监听路由时,确保依赖数组包含location或相关参数,否则可能无法正确触发。 - 使用
history.listen时,记得在组件卸载时移除监听,避免内存泄漏。 - 路由守卫的实现需要结合具体的权限逻辑,避免无限重定向。






