是否可以有多个< Switch>在React.js中? [英] Is it possible to have multiple <Switch> in React.js?

查看:46
本文介绍了是否可以有多个< Switch>在React.js中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am building a React project without Redux.

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

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

当用户登录时,第一开关将能够在主页(普通网站)和用户页面(仪表板)之间切换...然后,每一个也将是Switchers,因此Home将在Home组件之间切换,而UserPage将在UserPage组件之间切换.这有可能吗?

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.

推荐答案

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

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

这篇关于是否可以有多个&lt; Switch&gt;在React.js中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆