react-router / redux-simple router 加载深度路由

react-router / redux-simple router loading deep routes

本文关键字:深度 路由 加载 router redux-simple react-router      更新时间:2023-09-26

我正在努力解决使用react-router(使用redux-simple-router,fwiw)应该是一件简单的事情。

我定义了一些基本路线,如下所示:

<Route path="/" component={AppRoot}>
        <Route path="all" component={ScheduledReportList} mine={false}/>
        <Route path="mine" component={ScheduledReportList} mine={true}/>
        <Route path="report/:name" component={ScheduledReportList} mine={false}/>
</Route>

ScheduledReportList的Redner方法具有处理mine参数的功能,以及处理name道具的存在(或缺乏)的逻辑(截取不相关的片段)。

render() {
        const { name } = this.props.params;
        if (name != undefined && name != null) {
            // we are displaying details for a single report only
            let values = getScheduledReports();
            let currentReport = _.find(values, (report) => {
                return report.name == name;
            });
            if (this.props.route.mine) {
                return (
                    <MyReportDetails... />
                );
            } else {
                return (
                    <ReportDetails... />
                );
            }
        } else {
            // we are displaying all reports
            <snip...>
                values.map((report, i) => {
                    let anchor = undefined;
                    if (this.props.route.mine) {
                        anchor = <a onClick={() => {this.props.routeActions.replace('/myreport/' + report.name)}}>{report.name}</a>
                    } else {
                        anchor = <a onClick={() => {this.props.routeActions.replace('/report/' + report.name)}}>{report.name}</a>
                    }
                    <snip...>

我的问题是:客户端我可以很好地导航。使用调用routeActions.replace()routeActions.push()的锚点或跨度,那么一切都很好。问题特别在于当我处于"深层"路径(即其中带有斜杠的路径:/reports/fooReport/all)并且刷新页面,或者如果我尝试直接导航到它时。尝试在服务器端加载/reports/foo页面会给我一个SyntaxError: expected expression, got '<'错误,就好像它没有期望加载 webpack js 的索引.html一样。我可以很好地导航到/mine,这有点没有意义。

我错过了什么简单的东西来让它同时适用于直接和间接导航?谢谢!

好吧,我最终想通了,这与我一直在想的几乎没有关系。事实证明,我的getScheduledReports()方法脱离了将填充redux状态的假设,并且在导航到报告/任何不是立即的内容时。

从 redux 存储中为状态对象添加空/未定义的检查,并在不存在时返回 null 为我修复了它。填充商店并且报告可用后,我的组件会看到它并刷新。

您可以在react-router中进行深度路由,如下所示:

<Route path="/" component={Layout} >
    <IndexRoute component={Homepage} />
    <Route path="home" component={Homepage} />
    <Route path="bayaans" component={Bayaans} />
    <Route path="read-quran" component={Readquran} />
    <Route path="duas" component={Duas} />
    <Route path="events" component={Events} />
    <Route path="contact" component={Contactpage} />
</Route>
<Route path="/admin" component={AdminLayout} >
    <IndexRoute component={LoginPg} />
    <Route path="dashboard" component={Dashboard} />
    <Route path="list-bayaans" component={AdminBayaansPg} />
    <Route path="list-duas" component={AdminDuasPg} />
    <Route path="list-events" component={AdminEventsPg} />
</Route>