在React.js中可以有多个<Switch>吗?

Ame*_*vic 7 javascript reactjs react-router react-router-v4

我正在构建一个没有Redux的React项目.

我希望有两个,或者在这种情况下有3个不同的开关

当用户登录时,1st Switch将能够在主页(普通网站)和UserPage(仪表板)之间切换......然后每个都将成为切换器,因此Home将在Home组件之间切换,并且UserPage将在UserPage组件.这甚至可能吗?

                        Main Switcher 
     Home Page (Switch)              Dashboard
Home About Contact, Careers     My Profile, Courses, Classes, Donations...
Run Code Online (Sandbox Code Playgroud)

这就是项目的外观和结构.

Shi*_*hir 17

您可以根据需要使用任意数量的Switch组件.它只是呈现其下指定的所有路线的第一个匹配.

在你的情况下,这些方面的东西应该有效:

const Home = ({match}) => {
  return(
    <Switch>
      <Route path={match.url} exact={true} component={HomeDefaultComponent} />
      <Route path=`${match.url}/about` exact={true} component={About} />
      <Route path=`${match.url}/contact` exact={true} component={Contact} />
      <Route path=`${match.url}/careers` exact={true} component={careers} />
    </Switch>
  );
};

const Dashboard = ({match}) => {
  return(
    <Switch>
      <Route path={match.url} exact={true} component={DashboardDefaultComponent} />
      ... other Dashboard paths like Home component above
    </Switch>
  );
};

const App = () => {
  return(
    <Switch>
      <Route path='/home' component={Home} />
      <Route path='/dashboard' component={Dashboard} />
    </Switch>
  );
}
Run Code Online (Sandbox Code Playgroud)

  • 你能分享你的代码吗?一个github链接,或者codeandbox上的一个例子? (2认同)