我正在尝试使用新的 createBrowserRouter
函数和 RouterProvider
组件通过 react-router-dom
V6 实现到我的应用程序的路由。
当尝试实现loader
(请参阅路由themeLoader
)时,一旦创建router
,加载程序总是会被触发(请参阅应用程序.tsx)。
当然,这只发生在 theme
路由上,但由于它是在如此早期的阶段触发的,因此在身份验证开始之前就被触发,更不用说完成了,而且它调用的查询需要验证用户。
是否可以延迟加载程序
直到身份验证完成?
我已尝试 shouldRevalidate
但这并不能阻止 loader
第一次触发。
// PrivateRoute.tsx
function PrivateRoute(Props: PrivateRouteProps) {
console.log('PrivateRoute!');
// Auth logic here
if (isAuthenticating) return <div>Authenticating...</div>;
return !isUnauthorised ? <Outlet /> : <div>{'Unauthorised Access'}</div>;
}
// Theme.tsx
export async function themeLoader({ params }: LoaderProps) {
console.log('themeLoader!');
const query = store.dispatch(getTheme(params.theme));
const { data: theme } = await query;
query.unsubscribe();
if (theme === undefined)
throw new Response('Theme Not Found', { status: 404 });
return theme;
}
// Routes
const themeRoute = {
path: 'themes/:theme',
element: <ThemePage />,
loader: themeLoader
};
const parentRoute = {
path: '/',
element: <PrivateRoute authorisedRoles={MemberRoles} />,
errorElement: <RouteBoundary />,
children: [themeRoute]
};
// App.tsx
const router = createBrowserRouter([parentRoute]);
// themeLoader fires at this point...
function App() {
console.log('App!');
return <RouterProvider router={router} />;
}
// Console Output
themeLoader!
App!
RouteBoundary!
// Expected Output
App!
PrivateRoute!
themeLoader!
最佳答案
不,你不能。
加载器是并行调用的,因此它们不能互相阻塞或互相提供数据。
https://github.com/remix-run/react-router/issues/9188#issuecomment-1248180434
关于javascript - 创建路由器时,React Router Dom V6 加载器会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74174780/