gpt4 book ai didi

javascript - react-router v5 – 嵌套路由

转载 作者:行者123 更新时间:2023-11-29 15:07:40 24 4
gpt4 key购买 nike

即使在查看 SO 答案时我也无法弄清楚这一点。我的布局如下所示:

const Dashboard = (props) => (
<div className={styles.views}>
<Route
to="/dashboard/reports/create"
render={() => <ReportsForm {...props} />}
exact
/>
<Route
to="/dashboard/reports"
render={() => <Reports {...props} />}
exact
/>
</div>
);

const routes = [
{ path: '/', component: Home, exact: true },
{ path: '/dashboard', component: Dashboard },
{ path: '/about', component: About, exact: true },
{ path: undefined, component: Error404 },
];

const Routes = () => {
return (
<Switch>
{routes.map((config, i) => {
const key = `path-${config.path}`;
return <Route key={key} {...config} />;
})}
</Switch>
);
};
const App = compose(
withRouter,
connect(mapStateToProps),
)(() => {
return (
<Router history={history}>
<IntlProvider>
<Routes />
</IntlProvider>
</Router>
);
})

我有一个负责渲染多个选项卡的仪表板组件,所以转到 /dashboard/reports/create 应该只渲染 ReportsForm 组件,然后转到 /dashboard/reports 应该只呈现 Reports 组件。目前在两种情况下都呈现。

我做错了什么?

编辑当我尝试在仪表板中打印出 match Prop 时,它给了我这个——也许这会有所帮助:

{
"path": "/dashboard",
"url": "/dashboard",
"isExact": false,
"params": {}
}

最佳答案

除了您指出的声明 to 而不是 path 的拼写错误之外

您可以将 Dashboard 组件 Route 包装在 Switch

const Dashboard = (props) => (
<div className={styles.views}>
<Switch>
<Route
path="/dashboard/reports/create"
render={() => <ReportsForm {...props} />}
exact
/>
<Route
path="/dashboard/reports"
render={() => <Reports {...props} />}
exact
/>
</Switch>
</div>
);

如果这不起作用,您甚至可以使用初始路径将整个内容包装在 Route 中,如下所示:

const Dashboard = props => (
<div className={styles.views}>
<Route path="/dashboard/reports"> // <------------------
<Switch>
<Route path="/dashboard/reports/create" render={() => <ReportsForm {...props} />} exact />
<Route path="/dashboard/reports" render={() => <Reports {...props} />} exact />
</Switch>
</Route>
</div>
);

这是我刚刚创建的工作示例解决方案:https://stackblitz.com/edit/react-uih91e-router-nested?file=index.js

关于javascript - react-router v5 – 嵌套路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58327361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com