简体   繁体   中英

Why is react displaying all my components at once?

I have a simple app:

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

And I would expect that at the url / I would see the first component, and at any other url, I would see the second. The NotFound part is displaying how I would expect it too, but at / , I see the first component, then the second component displayed beneath it. NotFound is definitely not in my Feedback file. How do I use the router correctly so I only display the component I want it to?

Wrap your routes with <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'));

What does <Switch /> exactly do?

It renders the first child <Route> or <Redirect> that matches the location.

source

path="*" isn't actually supported in RRv4. Instead, a Route with no path property will always match. Combining the knowledge with the Switch component, you'll get the desired outcome. Switch will only render the first matching Route , so the idea is that if none of your other Route s match, then the last Route in your Switch component will render.

   <Switch>
        <Route path="/" exact={true} component={Feedback}/>
        <Route component={NotFound}/>
    </Switch>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM