2017-04-12 3 views
0

私はシンプルなアプリがありますなぜすべてのコンポーネントを同時に表示するのですか?

import React from 'react'; 
import { render } from 'react-dom'; 
import { BrowserRouter, Route } from 'react-router-dom'; 

import './css/hind.css'; 
import './css/splash.css'; 

import Feedback from './components/Feedback'; 
import NotFound from './components/NotFound'; 

render((
    <BrowserRouter> 
    <div className="add-100 dark-background"> 
     <Route path="/" exact={true} component={Feedback}/> 
     <Route path="*" component={NotFound}/> 
    </div> 
    </BrowserRouter> 
), document.getElementById('app')); 

をそして私は、URL /で、私は最初のコンポーネントを見ること、および任意の他のURLで、私は2番目を見るであろうことを期待します。 NotFoundの部分は、私がそれを期待する方法を表示していますが、/には、最初のコンポーネントが表示され、次に2番目のコンポーネントが表示されます。 NotFoundは間違いなく私のFeedbackファイルに含まれていません。ルータを正しく使用するにはどうしたらよいですか?

答えて

2

<Switch />で経路を折り返します。

import React from 'react'; 
import { render } from 'react-dom'; 
import { BrowserRouter, Route, Switch } from 'react-router-dom'; 

import './css/hind.css'; 
import './css/splash.css'; 

import Feedback from './components/Feedback'; 
import NotFound from './components/NotFound'; 

render((
    <BrowserRouter> 
    <div className="add-100 dark-background"> 
     <Switch> 
      <Route path="/" exact={true} component={Feedback}/> 
      <Route path="*" component={NotFound}/> 
     </Switch> 
    </div> 
    </BrowserRouter> 
), document.getElementById('app')); 

<Switch />は正確に何をしますか?

最初の子を、場所に一致する最初の子<Route>または<Redirect>にレンダリングします。

source

1

path="*"実際RRv4ではサポートされていません。代わりに、パスのないプロパティのルートは常に一致します。知識を組み合わせてSwitchコンポーネントを使用すると、望ましい結果が得られます。 Switchは最初のマッチングRouteをレンダリングするだけなので、他のRouteのどれも一致しない場合は、Switchコンポーネントの最後のRouteがレンダリングされます。

<Switch> 
     <Route path="/" exact={true} component={Feedback}/> 
     <Route component={NotFound}/> 
    </Switch> 
関連する問題