欢迎来到 TanStack Router 常见问题解答!在这里您将找到有关 TanStack Router 常见问题的答案。如果您有这里没有回答的问题,请随时在 TanStack Discord 中提问。
是的!尽管路由树文件(即 routeTree.gen.ts)是由 TanStack Router 生成的,但它本质上是您应用程序运行时的一部分,而不是构建产物。路由树文件是您应用程序源代码的关键部分,TanStack Router 在运行时使用它来构建您应用程序的路由。
您应该将此文件提交到 git,以便其他开发人员可以使用它来构建您的应用程序。
不,根路由总是被渲染,因为它是您应用程序的入口点。
如果您需要有条件地渲染路由组件,这通常意味着页面内容需要根据某些条件(例如用户身份验证)而有所不同。对于此用例,您应该使用 布局路由 或 无路径布局路由 来有条件地渲染内容。
您可以使用路由的 beforeLoad 函数中的条件检查来限制对这些路由的访问。
// src/routes/_pathless-layout.tsx
import { createFileRoute, Outlet } from '@tanstack/react-router'
import { isAuthenticated } from '../utils/auth'
export const Route = createFileRoute('/_pathless-layout', {
beforeLoad: async () => {
// Check if the user is authenticated
const authed = await isAuthenticated()
if (!authed) {
// Redirect the user to the login page
return '/login'
}
},
component: PathlessLayoutRouteComponent,
// ...
})
function PathlessLayoutRouteComponent() {
return (
<div>
<h1>You are authed</h1>
<Outlet />
</div>
)
}
// src/routes/_pathless-layout.tsx
import { createFileRoute, Outlet } from '@tanstack/react-router'
import { isAuthenticated } from '../utils/auth'
export const Route = createFileRoute('/_pathless-layout', {
beforeLoad: async () => {
// Check if the user is authenticated
const authed = await isAuthenticated()
if (!authed) {
// Redirect the user to the login page
return '/login'
}
},
component: PathlessLayoutRouteComponent,
// ...
})
function PathlessLayoutRouteComponent() {
return (
<div>
<h1>You are authed</h1>
<Outlet />
</div>
)
}
您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。