即使查看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
道具时,它给了我–也许这会有所帮助:
{
"path": "/dashboard",
"url": "/dashboard",
"isExact": false,
"params": {}
}
答案 0 :(得分:1)
除了您指出用于声明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