v6版本升级后路由跳转回调处理记录
React Router v6发布后,路由跳转的处理方式发生了较大变化。在升级过程中,我们遇到了多个路由跳转回调的问题。
问题场景
升级v6后,原有的history.listen()监听器失效,无法正确捕获路由变化。同时,useHistory Hook被移除,需要使用新的API来处理跳转回调。
解决方案
1. 使用useNavigate配合useEffect
import { useNavigate, useLocation } from 'react-router-dom';
function App() {
const navigate = useNavigate();
const location = useLocation();
useEffect(() => {
// 路由变化时的回调处理
console.log('路由跳转:', location.pathname);
// 执行相关逻辑
}, [location.pathname]);
const handleNavigate = () => {
navigate('/target');
};
}
2. 自定义Hook处理跳转监听
import { useEffect, useRef } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
function useRouterCallback() {
const location = useLocation();
const navigate = useNavigate();
const previousPath = useRef(location.pathname);
useEffect(() => {
if (previousPath.current !== location.pathname) {
// 路由变化回调
handleRouteChange(previousPath.current, location.pathname);
previousPath.current = location.pathname;
}
}, [location.pathname]);
const handleRouteChange = (from, to) => {
console.log(`从 ${from} 跳转到 ${to}`);
// 处理跳转后的业务逻辑
};
}
3. 在路由配置中添加回调
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
const router = createBrowserRouter([
{
path: '/',
element: <App />,
loader: async () => {
// 路由加载时的回调
return null;
}
}
]);
通过以上方案,成功实现了v6版本路由跳转的回调处理。
注意:升级过程中需要全面测试路由相关功能,确保所有跳转逻辑正常工作。

讨论