javascript - 创建路由器时,React Router Dom V6 加载器会触发

标签 javascript reactjs react-router-dom

我正在尝试使用新的 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/

相关文章:

javascript - 在javascript中设置动画时更改图像颜色

javascript - 当绑定(bind)中的值更改时, knockout 计算函数不会更新

javascript - Vue.js : Communicate with components that are down the DOM

javascript - JSX 中 Prop 的顺序重要吗?

javascript - 如何将数组添加到字符串而不在 JS 中展平它们?

reactjs - Froala 所见即所得编辑器未显示 React 中的所有工具栏按钮

javascript - react-export-excel 如何在导出时隐藏 excel 中的列?

javascript - 将参数传递给动态生成的 react 路线

javascript - 使用 react-router-dom 网页上没有显示任何内容

reactjs - React-router v6 window.scrollTo 不起作用