即使在查看 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/