React routing always loads the same component

时光毁灭记忆、已成空白 提交于 2021-01-28 11:09:43

问题


I am trying to add routing to my simple application:

import Home from './componantes/Home'
import Contact from './componantes/Contact'
import Aboutus from './componantes/Aboutus'
import { Route, Link, BrowserRouter as Router} from 'react-router-dom'
const routing = (
    <Router>
      <div>
        <Route path="/" component={Home} />
        <Router path="/contact" component={Contact} />
        <Router path ="/about" component={Aboutus} />
      </div>
    </Router>
  )

ReactDOM.render(routing, document.getElementById('root'));

but whatever url I try to access /contact or /about it always takes me to home component.

my aboutus componant:

import React from 'react'

export default class Contact extends React.Component{
    render() {           
        return (
            <h1>Contact componant</h1>
        )
    }
}

What's going wrong here?


回答1:


You need to add exact prop to the / Route to tell that you only want it to match when the location matches exactly.

Also you have typos in router definition, instead of Router you need to use Route for contact and about us.

So these lines must be corrected:

<Router path="/contact" component={Contact} /> 
<Router path ="/about" component={Aboutus} />
   <Router>
      <div>
        <Route path="/" exact component={Home} />
        <Route path="/contact" component={Contact} />
        <Route path ="/about" component={Aboutus} />
      </div>
    </Router>

Codesandbox




回答2:


For routes you can use Switch. Switch decide which router is called and second one is put your component in ordered way like home at the bottom.So , our app will check /contact and /about before / route.you can check more about react-router-dom on official doc.

import Home from './componantes/Home'
import Contact from './componantes/Contact'
import Aboutus from './componantes/Aboutus'
import { Route, Link, BrowserRouter as Router , Switch } from 'react-router-dom'
const App = (
    <Router>
      <Switch>
        <Route path="/contact" component={Contact} />
        <Route path ="/about" component={Aboutus} />
        <Route path="/" component={Home} />
      </Switch>
    </Router>
  )

ReactDOM.render(<App/>, document.getElementById('root')); //need to change 



回答3:


Another option is to use exact prop for your home route, so it will be triggered only when the url is /. Also routing has to be a valid react component and rendered accordingly:

const Routing = () =>  (
    <Router>
        <Route exact path="/" component={Home} />
        <Router path="/contact" component={Contact} />
        <Router path ="/about" component={Aboutus} />
    </Router>
  )

ReactDOM.render(<Routing/>, document.getElementById('root'))


来源:https://stackoverflow.com/questions/59786186/react-routing-always-loads-the-same-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!