我正在尝试将我的路由拆分为许多文件,为了实现这一点,我有一个名为 routes 的中心文件。
import React from "react";
import { Router, Route, Switch } from "react-router-dom";
import history from "./History";
import StreamRoutes from "./stream/StreamRoutes";
const Routes = props => {
return (
<React.Fragment>
<Router history={history}>
<Switch>
<Route path="/" exact component={props => <h1>hello world</h1>} />
<StreamRoutes />
</Switch>
</Router>
</React.Fragment>
);
};
export default Routes;
然后是所有主要组件的路由文件,如下所示:
import React from "react";
import { Route } from "react-router-dom";
import StreamCreate from "./components/StreamCreate";
import StreamEdit from "./components/StreamEdit";
import StreamList from "./components/StreamList";
import StreamShow from "./components/StreamShow";
const StreamRoutes = props => {
return (
<React.Fragment>
<Route path="/streams" exact component={StreamList} />
<Route path="/streams/new" exact component={StreamCreate} />
<Route path="/streams/:id" exact component={StreamShow} />
<Route path="/streams/edit/:id" exact component={StreamEdit} />
</React.Fragment>
);
};
export default StreamRoutes;
除非我尝试访问"/streams/new"或"/streams/:id",否则这有效,在任何这些情况下,路由器都会同时显示这两个组件。
我想知道如何解决这个问题或更好的方法来组织我的路线将不胜感激。
可以使用
像FuzzyTree建议的正则表达式,但这在更大的项目中可能会变得混乱。我建议将 StreamRoutes 中的React.Fragment
替换为 Switch
。这样它的工作方式就像你期望的那样。