reactjs - 在 react-router 5.1 中动态渲染路由
问题描述
我正在尝试将我手动声明的路由组件(在 Route 中)转换为动态渲染,如下所示:
const routes = [
{ path: '/cars', exact: true, component: Cars },
{ path: '/car/:id', component: Car },
{ path: '/login', component: Login },
]
export default function Routing() {
return (
<BrowserRouter >
<Switch>
{routes.map(({ component, ...rest }, index) => {
return (
<Route key={index} {...{ rest }}>
{React.createElement(component)}
</Route>
)
})}
<Redirect to="/homes" />
</Switch>
</BrowserRouter>
)
}
我也尝试过以下方法:
{routes.map(({ component: Cmp, ...rest }, index) => {
return (
<Route key={index} {...{ rest }}>
<Cmp />
</Route>
)
})}
但以上都没有导致路线。当点击之前有效的链接时,现在什么也没有发生。知道可能出了什么问题吗?
解决方案
你必须做{...rest}
而不是{...{ rest }}
让它工作。
{...rest}
将破坏对象,而{...{rest}}
将创建另一个对象,例如{rest: { path: '/login'}}
<Router >
<Switch>
{routes.map(({ component, ...rest }, index) => {
return (
<Route {...rest} component={component} />
)
})}
</Switch>
</Router>
推荐阅读
- node.js - 带有 Fusionauth passport-oauth OAuth2Strategy 错误的节点:无法获取访问令牌
- java - 当前日期函数在 JPA 中返回昨天的日期
- python - 使用 Python 中的 Selenium 在 YouTube 视频中查找评论数的 CSS 选择器应该是什么?
- oracle - Oracle DB 用户只能在 localhost 上登录
- r - 如何在 Shiny 应用程序中将数据记录到表中
- java - Android Studio:setOnDateChangeListener 不起作用
- linux - 从 Linux 上的 wifi 热点托管问题
- python - Windows 10 上的 Python 套接字问题
- python - python函数和梅森数
- python - 使用 **kwargs 时,dicts 的语法如何变化(因为显然键必须是字符串)?