React 路由总是加载相同的组件 [英] React routing always loads the same component

查看:30
本文介绍了React 路由总是加载相同的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向我的简单应用程序添加路由:

从'./componantes/Home'导入Home从'./componantes/Contact'导入联系人从'./componantes/Aboutus'导入关于我们import { Route, Link, BrowserRouter as Router} from 'react-router-dom'常量路由 = (<路由器><div><Route path="/" component={Home}/><Router path="/contact" component={Contact}/><Router path="/about" component={Aboutus}/>

</路由器>)ReactDOM.render(routing, document.getElementById('root'));

但是无论我尝试访问 /contact/about 的任何 url,它总是将我带到主页组件.

我的关于我们组件:

从 'react' 导入 React导出默认类 Contact 扩展 React.Component{使成为() {返回 (<h1>接触组件</h1>)}}

这里出了什么问题?

解决方案

您需要添加 exact prop 到 / 路由告诉你只希望它在位置完全匹配时匹配.

此外,您在路由器定义中也有错别字,您需要使用 Route 而不是 Router 来联系和了解我们.

因此必须更正这些行:

 <路由器><div><Route path="/" 精确组件={Home}/><Route path="/contact" component={Contact}/><Route path="/about" component={Aboutus}/>

</路由器>

代码沙盒

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?

解决方案

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

这篇关于React 路由总是加载相同的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆