Is it possible to have multiple <Switch> in React.js?

痴心易碎 提交于 2021-01-20 15:39:19

问题


I am building a React project without Redux.

I would love to have two, or in this case 3 different Switches

1st Switch will be able to Switch between Home page (normal website) and UserPage (Dashboard) when user is logged in... Then each of this will be Switchers as well, so Home will Switch among Home components, and UserPage will switch among UserPage components. Is this even possible?

                        Main Switcher 
     Home Page (Switch)              Dashboard
Home About Contact, Careers     My Profile, Courses, Classes, Donations...

This is how project should look like and should be structured.


回答1:


You can use as many Switch components as you want. It simply renders the first match of all the routes specified under it.

Something along these lines should work, in your case:

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>
  );
}


来源:https://stackoverflow.com/questions/49208310/is-it-possible-to-have-multiple-switch-in-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!