React router v5:需要动态路由中的嵌套路由

特别是react-router-dom v5.2.0 我有一个项目列表,所有这些项目都需要自己的页面,并且在该动态路由中,我想要一些嵌套路由。

可以这样想:

  • myapp.com/:item(主项目页面)

  • myapp.com/:item/about(关于项目页面)

  • myapp.com/:item/faq(常见问题解答项目页面)

问题是,按照我实现它的方式,每个嵌套/:item/whatever页面都会收到 404。这是我的路由当前的样子:

const App = ({}) => {

    return (

        <Router>

            <Switch>

                <Route exact path='/:id' component={Item}>

                </Route>

            </Switch>

        </Router>

    )

}


const Item = ({ match }) => {

    return (

        <div>

            TODO: Item {match.url}

            <Switch>

                <Route path={`${match.path}/about`}>

                    <h1>TODO: About</h1>

                </Route>

                <Route path={`${match.path}/faq`}>

                    <h1>TODO: FAQ</h1>

                </Route>

            </Switch>

        </div>

    );

};

就目前情况而言,我可以获得 的页面/:item,但如果我尝试转到它们的嵌套路由,则会收到 404。我的设置有问题吗?我怎样才能让它发挥作用?

请注意,我已经尝试了许多不同的变体:

  • App组件中的嵌套路由

  • 有和没有Switch包装纸

  • 将组件Route作为component嵌套组件的 prop传递给

编辑:决定包含我的Item组件的一个版本,其中我有我能想到的路线的所有变体/about


芜湖不芜
浏览 114回答 1
1回答

宝慕林4294392

所以看来我的处理方式完全错误。对于我想做的事情,我的嵌套路由需要位于组件上App,或者至少位于第一个Switch包装器的根上。所以基本上这就是解决方案:const App = ({}) => {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <Router>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Switch>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Route exact path='/:id' component={Item}/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Route exact path='/:id/about' component={() => <div>TODO: About</div>}/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Route exact path='/:id/faq' component={() => <div>TODO: FAQ</div>}/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </Switch>&nbsp; &nbsp; &nbsp; &nbsp; </Router>&nbsp; &nbsp; )}我仍然很困惑,因为文档显示的内容有所不同,但无论如何,这就是解决问题的方法。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript