反应路由器 4 开关显示两个组件

react router 4 switch showing two components

我试图将我的路线分成许多文件,为了实现这一点,我有一个名为路线的中央文件。

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。这样它会像您期望的那样工作。