Switch

Konumla eşleşen ilk <Route> veya <Redirect> childını oluşturur.

Route grubu kullanmaktan farkı nedir?

<Switch>, yalnızca bir route oluşturması bakımından benzersizdir. Aksine, konumla eşleşen her bir <Route>, kapsamlı bir şekilde oluşturulur. Bu kodu düşünün:

<Route path="/about" component={About}/>
<Route path="/:user" component={User}/>
<Route component={NoMatch}/>

URL /about ise, <About>, <User> ve <NoMatch> hepsi eşleştiğinden render edilecektir. Bu tasarımlarımıza sidebar, breadcrumb, bootstrap tabları vb. gibi birçok şeyi oluşturmamıza izin veriyor.

Bununla birlikte bazen render etmek için yalnızca bir tane <Route> seçmek istiyoruz. Eğer konum /de olursa, aynı zamanda /:user ile eşleştirmek istemiyoruz (ya da “404” sayfamızı gösterelim). Switch ile yapabilirsiniz:

import { Switch, Route } from 'react-router'

<Switch>
  <Route exact path="/" component={Home}/>
  <Route path="/about" component={About}/>
  <Route path="/:user" component={User}/>
  <Route component={NoMatch}/>
</Switch>

Bu, eşleştirilen <Route>, öncekiyle aynı konumda oluşturulduğundan, animasyonlu geçişler için de yararlıdır.

<Fade>
  <Switch>
    {/* Burada sadece bir child olacak */}
    <Route/>
    <Route/>
  </Switch>
</Fade>

<Fade>
  <Route/>
  <Route/>
  {/* Burada her zaman iki child olacak,
  bir tane null bile olsa
  geçişler biraz daha hantaldır */}
</Fade>

Parametreleri

location: object

Geçerli geçmiş konumu yerine (genellikle mevcut tarayıcı URL’i) child elementlerini eşleştirmek için kullanılacak bir konum objesidir.

children: node

<Switch>in tüm childları <Route> veya <Redirect> elementleri olmalıdır. Sadece mevcut konumla eşleşen ilk child render edilecektir.

<Switch>e bir konum propsu verilirse, eşleşen child elemanındaki konum propsu geçersiz kılacaktır.

<Switch>
  <Route exact path="/" component={Home}/>

  <Route path="/users" component={Users}/>
  <Redirect from="/accounts" to="/users"/>

  <Route component={NoMatch}/>
</Switch>

Gelişmiş kılavuzlar sonlanmıştır. Bu aşamadan sonra Uygulamalı Eğitime geçiş yapılacaktır.

Sıradaki Eğitim: Basit Router Örneği