欢迎来到 TanStack Router 常见问题解答!在这里,您将找到关于 TanStack Router 的常见问题的解答。如果您有这里没有解答的问题,请随时在 TanStack Discord 中提问。
是的!虽然路由树文件(即 routeTree.gen.ts)是由 TanStack Router 生成的,但它本质上是面向应用程序运行时的。它不是构建产物。路由树文件是应用程序源代码的关键部分,TanStack Router 使用它在运行时构建应用程序的路由。
您应该将此文件提交到 git,以便其他开发人员可以使用它来构建您的应用程序。
不,根路由始终会被渲染,因为它是应用程序的入口点。
如果您需要有条件地渲染路由的组件,这通常意味着页面内容需要根据某些条件(例如用户身份验证)而有所不同。对于这种情况,您应该使用 Layout Route 或 Pathless Layout Route 来有条件地渲染内容。
您可以使用路由的 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 万名开发者。