是否可以在React.js中有多个<Switch>?
Is it possible to have multiple <Switch> in React.js?
我正在构建一个没有 Redux 的 React 项目。
我希望有两个,或者在本例中有 3 个不同的开关
第一个开关将能够在用户登录时在主页(普通网站)和用户页面(仪表板)之间切换...
然后每一个这也将是切换器,因此 Home 将在 Home 组件之间切换,而 UserPage 将在 UserPage 组件之间切换。这甚至可能吗?
Main Switcher
Home Page (Switch) Dashboard
Home About Contact, Careers My Profile, Courses, Classes, Donations...
这就是项目的外观和结构。
您可以根据需要使用任意数量的 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>
);
}
我正在构建一个没有 Redux 的 React 项目。
我希望有两个,或者在本例中有 3 个不同的开关
第一个开关将能够在用户登录时在主页(普通网站)和用户页面(仪表板)之间切换... 然后每一个这也将是切换器,因此 Home 将在 Home 组件之间切换,而 UserPage 将在 UserPage 组件之间切换。这甚至可能吗?
Main Switcher
Home Page (Switch) Dashboard
Home About Contact, Careers My Profile, Courses, Classes, Donations...
这就是项目的外观和结构。
您可以根据需要使用任意数量的 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>
);
}