我有一个使用 u/tanstack/react-router 的路由设置,我需要根据活动路由有条件地渲染组件。具体来说,我希望仅当路线为 /instructor-dashboard 时才渲染 InstructorDashboardComponent,而当路线为 /instructor-dashboard/course-builder 时,应渲染 CourseBuilderComponent。
目前,使用给定的代码,InstructorDashboardComponent 始终呈现在文件顶部,即使路径是 /instructor-dashboard/course-builder 也是如此,导致 InstructorDashboardComponent 和 CourseBuilderComponent 都被显示。
如何根据活动路线有条件地渲染 InstructorDashboardComponent 以确保当路线为 /instructor-dashboard/course-builder 时它不会出现?
这是当前的路线设置:
主要路线:
import { createFileRoute, Outlet } from "@tanstack/react-router";
import MaxWidthWrapper from "../components/common/MaxWidthWrapper";
import InstructorDashboardComponent from "../components/InstructorDashboard/InstructorDashboardComponent";
export const Route = createFileRoute("/instructor-dashboard")({
loader: async () => {
// load with Tanstack query
},
component: () => (
<MaxWidthWrapper className="h-screen">
<InstructorDashboardComponent />
<Outlet />
</MaxWidthWrapper>
),
});
支线:
import { createFileRoute } from "@tanstack/react-router";
import MaxWidthWrapper from "../components/common/MaxWidthWrapper";
import CourseBuilderComponent from "../components/InstructorDashboard/CourseBuilderComponent";
export const Route = createFileRoute("/instructor-dashboard/course-builder")({
loader: async () => {
// load with Tanstack query
},
component: () => (
<MaxWidthWrapper className="h-screen">
<CourseBuilderComponent
courseContent={[]}
courseTabInfo={{
id: 123,
courseName: "",
longDescription: "",
shortDescription: "",
supportedGrades: "",
supportedLanguages: "",
}}
/>
</MaxWidthWrapper>
),
});
我需要进行哪些更改才能根据活动路线有条件地渲染这些组件?
没有这方面的文档。我尝试根据 TanStack 路由器提供的 props 调用条件渲染:
import { createFileRoute, Outlet } from "@tanstack/react-router";
import MaxWidthWrapper from "../components/common/MaxWidthWrapper";
import InstructorDashboardComponent from "../components/InstructorDashboard/InstructorDashboardComponent";
export const Route = createFileRoute("/instructor-dashboard")({
loader: async () => {
// load with Tanstack query
},
component: () => (
<MaxWidthWrapper className="h-screen">
** {Route.fullPath === "/instructor-dashboard" ? (
<InstructorDashboardComponent />
) : (
<Outlet />
)}**
</MaxWidthWrapper>
),
});
但这将始终评估为 true,因为子路由嵌套在主路由内。
使用 tanstack Router 的 useLocation hook。
import { createFileRoute, Outlet } from "@tanstack/react-router";
import MaxWidthWrapper from "../components/common/MaxWidthWrapper";
import InstructorDashboardComponent from "../components/InstructorDashboard/InstructorDashboardComponent";
export const Route = createFileRoute("/instructor-dashboard")({
loader: async () => {
// load with Tanstack query
},
component: Component
});
function Component() {
const location = useLocation()
return(
<MaxWidthWrapper className="h-screen">
{location.pathName === "/instructor-dashboard" ? (
<InstructorDashboardComponent />
) : (
<Outlet />
)}
</MaxWidthWrapper>
)
}