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

时间:2018-12-29 20:40:19

标签: reactjs react-router react-router-v4 react-router-dom

我正在尝试将路线分成多个文件,为实现这一目标,我有一个名为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”时,此方法均有效,在任何情况下,路由器都会同时显示两个组件。

我想知道如何解决此问题,或者更好地组织路线的方法将受到赞赏。

1 个答案:

答案 0 :(得分:1)

可以使用类似FuzzyTree的正则表达式,但是在更大的项目中可能会变得混乱。我建议用React.Fragment替换StreamRoutes中的Switch。这样,它就可以像您期望的那样工作。