我在 React 应用程序中使用 @tanstack/react-router 和 @tanstack/react-query。我已经设置了一个 QueryClient 来处理错误,并在发生 401 未经授权错误时重定向到登录页面。但是,重定向后,URL 更改为 /login,但内容不会更新以显示登录页面,直到我手动与页面交互(例如,单击链接)。
import { StrictMode } from "react";
import ReactDOM from "react-dom/client";
import { RouterProvider, createRouter, redirect } from "@tanstack/react-router";
import { routeTree } from "./routeTree.gen";
import {
QueryCache,
QueryClient,
QueryClientProvider,
} from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import "./index.css";
import "./i18n";
const queryClient = new QueryClient({
queryCache: new QueryCache({
onError: (error) => {
router.navigate({ to: "/login" });
},
}),
});
export const router = createRouter({ routeTree, context: { queryClient } });
declare module "@tanstack/react-router" {
interface Register {
router: typeof router;
}
}
const rootElement = document.getElementById("root")!;
if (!rootElement.innerHTML) {
const root = ReactDOM.createRoot(rootElement);
root.render(
<StrictMode>
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
</StrictMode>
);
}
您可以通过在父组件中使用 beforeLoad 来检查未授权尝试。喜欢:
// src/routes/_authenticated.tsx
export const Route = createFileRoute('/_authenticated')({
beforeLoad: async ({ location }) => {
if (!isAuthenticated()) {
throw redirect({
to: '/login',
search: {
// Use the current location to power a redirect after login
// (Do not use `router.state.resolvedLocation` as it can
// potentially lag behind the actual current location)
redirect: location.href,
},
})
}
},
})