由于您是新手,我将花更多时间用示例进行解释,并添加一些您可能希望方便使用的东西。
正如 Iddler 所说,Switch 或多或少类似于任何其他语言中的“Switch case”条件,但通常以它找到的第一个匹配项结束。
<Switch>
<Route path="/home" component={Home} />
<Route path="/about" component="{About} />
</Switch>
这是其最基本用途的一个示例。 Switch 确定块或条件的开始和结束。每个 Route 检查当前路径。假设我们正在处理“www.test.com”。所有“www.test.com”都是根“/”。因此 Route 检查根之后的路径。因此,如果您有“www.test.com/home”,则“/home”位于根之后,因此将在上面的示例中加载“Home”组件,如果您有“www.test.com/about”,则“关于”组件已加载。
请注意,您可以使用任何名称。组件和路径不必相同。
在某些情况下,您可能希望使用 exact 来匹配确切的路径。当您有类似的路径时,这很有用。例如“/shop”和“/shop/shoes”。使用 exact 确保 Switch 匹配确切的路径,而不仅仅是第一个。
例如:
<Switch>
<Route exact path="/shop" component={Shop} />
<Route exact path="shop/shoes" component="{Shoes} />
</Switch>
您也可以使用不带<Switch> 的<Route... />。
例如:
<Route path="/home" component={Home} />
与直接加载组件不同,您只需加载像 <Home /> 这样的组件,路由器使用 URL。
最后,<Route... /> 路径可以使用 url 数组来加载相同的组件。
例如:
<Switch>
<Route path={[ "/home", "/dashboard", "/house", /start" ]} component={Home} />
<Route exact path={[ "/about", "/about/management", "/about/branches" ]} component="{About} />
</Switch>
我希望这会有所帮助。如果您需要任何形式的澄清,请告诉我。 :)
更新:
您不必总是以相同的格式编写路由器。以下是您可以使用的另一种格式;
<Router>
<Switch>
<Route path="/home">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
</Switch>
</Router>
现在有像 am in 这样的实例,您希望能够处理输入错误 URL 时显示的内容。就像一个 404 页面。您可以在没有路径的情况下使用 Router。就像一个常规的 switch 语句一样,它成为你的默认值。
<Switch>
<Route path="/home" component={Home} />
<Route path="/about" component="{About} />
<Route component="{PageNotFound} />
</Switch>