首页 > 解决方案 > React Router v4 - 嵌套路由不起作用

问题描述

这些是我在 Router.js 中的主要路线

const Routes = () => {
    return ( 
        <Switch>
            <Route path="/" exact component={HomePage} />
            <Route path="/dashboard" component={Dashboard} />
        </Switch>
    );
}

这些是我在主页下的嵌套路由。现在仪表板和主页正在工作,但忘记密码和注册不工作。我只能看到没有错误的空白页。

render() {
     const {match} = this.props;
    return (
        <div className="container home-grid">
            <div className="featured">
                <Featured />
            </div>
            <div className="home-forms">
                <div className="logo">
                    <Logo />
                </div>
                <TransitionGroup className="route-page">
                    <CSSTransition
                        key={location.pathname}
                        timeout={{ enter: 800, exit: 800 }}
                        classNames="page"
                    >
                        <section className="route-section">
                            <Switch>
                                <Route exact path={match.path} component={SignIn}/>
                                <Route path={`${match.path}forgot-password`} component={ForgotPassword} />


                            </Switch>
                        </section>
                    </CSSTransition>
                </TransitionGroup>
                <div className="footer-text">
                    <Text specialClass="footer"></Text>
                </div>
            </div>
        </div>
    )
}

登录正在渲染,但其他路由没有。我究竟做错了什么?

标签: javascriptreactjsreact-router

解决方案


当您到达路由时发生的情况/forgot-password是 HomePage 路由不再匹配,因为exact导致卸载整个 Home 组件,因此它也卸载了子路由。

您必须将子路由上移一级,例如在您定义主路由的 Routes.js 中。或者您可以删除exactHome 组件并将其作为呈现所有常见元素(例如页眉和页脚)的组件进行威胁,但在这种情况下,我不会将其称为 Home,但可能会Main这样。


推荐阅读