【问题标题】:Create multiple routes and nested routes from array从数组创建多个路由和嵌套路由
【发布时间】:2021-03-02 03:21:15
【问题描述】:

我有一个项目数组,每个项目都需要有自己的路由和其他一些嵌套路由。 可以这样想:

  • myapp.com/[item](主项目页面)
  • myapp.com/[item]/about(关于项目页面)
  • myapp.com/[item]/faq(常见问题项目页面)

问题是我有一个项目列表,理想情况下,每个项目都应该有自己的 aboutfaq 页面。如果我能够遍历一个数组并渲染每个 Route,那就太好了。像这样的:

const items = [
    { id: 1, name: 'item1' },
    { id: 2, name: 'item2' },
    { id: 3, name: 'item3' },
    { id: 4, name: 'item4' }
]

const App = () => {
    return (
        <Router>
            <Switch>
                {items.map(({ id, name }, index) => (
                    <React.Fragment key={id}>
                        <Route path={`/${name}`} component={<ItemComponent/>}/>
                        <Route path={`/${name}/about`} component={<AboutItemComponent/>}/>
                        <Route path={`/${name}/faq`} component={<FaqItemComponent/>}/>
                    </React.Fragment>
                ))}

                <Route path="*" render={() => <div>Not Found</div>} />
            </Switch>
        </Router>
    )
}

不幸的是,这不起作用。出现以下问题:

  • 实际上只有第一个项目获得了路由。其他的什么都不渲染(没有 404 或任何东西,但我得到了一个空白页面)。
  • 如果我尝试访问嵌套路由,我会得到 404,即使对于实际呈现的一个路由也是如此。

如果我只通过数组来渲染一条路线,它们就可以正常工作。我指的是这样的事情:

const App = () => {
    return (
        <Router>
            <Switch>
                {items.map(({ id, name }, index) => (
                    <Route path={`/${name}`} component={<ItemComponent/>}/>
                ))}

                <Route path="*" render={() => <div>Not Found</div>} />
            </Switch>
        </Router>
    )
}

但对我来说,要到达我需要的所有路线,就必须做一堆.map(),这似乎适得其反。必须有一个更简单和正确的方法来完成这项工作。有什么建议吗?

谢谢!

【问题讨论】:

    标签: javascript reactjs react-router react-router-dom react-router-v5


    【解决方案1】:

    我不确定您是否需要创建所有这些路线。您可以通过使用 URL 参数只使用三个:

    const App = () => {
        return (
            <Router>
                <Switch>
                  <Route path="/:item/about" component={<AboutItemComponent/>}/>
                  <Route path="/:item/faq" component={<FaqItemComponent/>}/>
                  <Route exact path="/:item" component={<ItemComponent/>}/>
                </Switch>
            </Router>
        )
    }
    

    React Router 网站上也有一个示例显示了这一点 - https://reactrouter.com/web/example/url-params

    正如您在他们的示例中所见,那些被渲染的组件随后可以访问 URL 参数并为该项目渲染正确的信息。

    如果您确实有比这更复杂的路由结构,您可以开始查看他们的Route Config example 和他们拥有的react-router-config 模块。

    但是,对于您提供的示例路由,我会保持简单,只使用 URL 参数。

    【讨论】:

    • 最初我确实想过做你的例子,但我不希望任何东西被接受,只接受我的项目数组中的任何东西。其他任何事情都应该执行 404。路由配置示例可能是我正在寻找的更多内容。很快就会试一试。
    • 您可以处理的一种方法是访问 URL 参数并改为呈现 404 内容。例如,在FaqItemComponent 中,您可能会获得 URL 参数,它可能与您的预期完全不同。然后您可以只显示您的 404 内容(可能作为单独的组件导入)。这样做的好处是您在地址栏中保留了错误的 URL。当您可能需要先调用 API 来验证是否存在某些东西时,它也能很好地工作。如果您转到 google.com/blah 之类的网址,您会看到 Google 会执行此操作
    猜你喜欢
    • 2018-03-24
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    • 2019-08-13
    • 2016-08-18
    • 2020-07-18
    • 2013-08-19
    • 1970-01-01
    相关资源
    最近更新 更多