TLDR:我正在尝试弄清楚如何布置嵌套的路线和我的组件,以便可以根据路线替换一个组件。
用超级简单的术语来说,我正在尝试构建一个应用程序,使教师可以看到他们在大学教授的课程。
应用程序的路由为:
/dashboard
:呼叫后端以检查教师的帐户上是否设置了默认的大学,如果没有,则显示一个大学选择器对话框,教师可以在其中选择一个默认的大学。有了默认的大学(例如COLLEGE1
)后,请重新路由到下一条路线(下一个要点)/dashboard/college/COLLEGE1
:获取大学教授的课程的元数据。/dashboard/college/COLLEGE1/class/CLASS1
:显示COLLEGE1
中单个类的元数据。通过单击项目符号2中的课程可以访问此路由。这是静态交互时的样子的粗略模拟(我为每个组件上了颜色,因此您在响应时更容易引用它们):
但是,我只是无法弄清楚嵌套路由+组件层次结构,这会让我明白这一点。
到目前为止,我的层次结构是:
<Home>
<Header/>
<!-- content in header -->
</Header>
<MainContent>
<!-- Either loading, for e.g. to fetch permissions -->
<Loading />
<!-- OR display navigation + content -->
<MainContentPage>
<!-- show navigation pane on left, and then choose from report / T and Cs / Contact -->
<Navigation>
<CurrentCollegeInfo />
<DashboardLink />
<TermsAndConditionsLink />
<ContactUsLink />
</Navigation>
<ReportPage>
<!-- Either Loading -->
<Loading />
<!-- OR have user select default college -->
<DefaultCollegePickerPopup />
<!-- OR show college report or class details -->
<CollegeReportPage />
<ClassDetailsPage />
<!-- OR error pages: Not Found, 500, etc. -->
<ErrorPage />
</ReportPage>
<TermsAndConditionsPage />
<ContactUsPage />
</MainContentPage>
</MainContent>
</Home>
如何在此处插入路由管理(顺便说一句,我正在使用react-router库),以便在ReportPage组件中:
/dashboard
(从后端加载默认大学或要求用户选择一个学院时)/dashboard/college/COLLEGE1
并获取大学报告/dashboard/college/COLLEGE1/class/CLASS1
并获取类详细信息?这是否不可能,我宁愿找出另一种流程?
答案 0 :(得分:1)
因此,如果我理解正确,您想根据用户所在的端点使用react-router
加载不同的组件吗?这是100%可能的。您只需将要针对特定路线显示的组件作为组件属性传递。
您还可以在路径中使用参数,因此在您的示例中,您有/dashboard/COLLEGE1
...我假设您需要动态地设置它以允许任何大学。这是通过将参数放置在路径中来完成的,例如/dashboard/:somevariablename
。
<Route
// exact
path={"/dashboard"}
// path={"/dashboard/:collegeId"}
// path={"/dashboard/:collegeId/classes/:classId"}
component={ComponentToPass}
/>
如果您为用户可以访问的每个可能的组件/页面创建一个Route
,并将其包装在<Switch>
组件中,它将仅显示一个组件。不过,您也可以跳过<Switch>
并向端点添加多条路由。
我假设您需要在相应的组件中使用collegeId和classId。如果您正在使用功能性React,请使用const { VARNAME } = useParams()
来检索您正在使用的参数。如果您使用的是基于类的react,则只需调用this.props.match.VARNAME
。 -两者显然都在要显示/使用的组件内部使用。
因此,稍微修改一下代码(可以在专用的路由组件中完成),这是一个简单的示例。
import {HashRouter, Switch, Route} from "react-router-dom"
import DefaultCollegePickerPopup from './wherever'
import CollegeReportPage from './wherever'
import ClassDetailsPage from './wherever'
function RouterComponent(props) {
return (
<HashRouter>
<Switch>
<Route
exact
path={"/dashboard"}
component={DefaultCollegePickerPopup}
/>
<Route
exact
path={"/dashboard/:collegeId"}
component={CollegeReportPage}
/>
<Route
exact
path={"/dashboard/:collegeId/class/:classId"}
component={ClassDetailsPage}
/>
</Switch>
</HashRouter>
)
}
function CollegeReportPage(props) {
const { collegeId } = useParams();
return (
<div>College report for {collegeId}</div>
)
}
class CollegeReportPage extends React.Component {
render() {
const { collegeId } = this.props.match
return (
<div>College report for {collegeId}</div>
)
}
}
如果您还没有看过,我会的。它提供了大量有用的信息。