我正在尝试学习反应路线配置。我在一个地方添加了所有导航链接,这是入口点index.js,我的期望是当有人对导航期间配置的路径作出反应时,应该在briwser中加载相应的组件。我在我的输入文件index.js中添加了所有路径路径,如下所示:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app.js';
import { BrowserRouter, Route, hashHistory } from 'react-router-dom';
import AboutUs from './AboutUs.js';
import ContactUs from './ContactUs.js';
import {Switch} from 'react-router';
ReactDOM.render(
(<BrowserRouter>
<Switch>
<Route path="/" component={App}/>
<Route path="/about-us" component={AboutUs}/>
<Route path="/contact-us" component={ContactUs}/>
</Switch>
</BrowserRouter>)
, document.getElementById('app'));
app.js如下:
import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
class App extends Component {
constructor(props){
super(props);
}
render() {
return (
<div>
<h1>React Router Tutorial</h1>
<ul role="nav">
<li><Link to="/about-us">About</Link></li>
<li><Link to="/contact-us">Contact</Link></li>
</ul>
</div>
)
}
}
export default App;
AboutUs.js如下:
import React, { Component } from 'react';
class AboutUs extends Component {
render(){
return(
<div>
AboutUs
</div>
);
}
}
export default AboutUs ;
ContactUs.js如下:
import React, { Component } from 'react';
class ContactUs extends Component{
render(){
return(
<div>
Contact Us
</div>
);
}
}
export default ContactUs;
但是当我点击任何链接/ about-us或/ contact-us时,它不会加载任何内容并显示相同的app.js,如下所示
有人可以告诉我为什么会这样吗?
答案 0 :(得分:0)
Switch
renders the first route that it matches in the order that it is given.
<BrowserRouter>
<Switch>
<Route path="/about-us" component={AboutUs}/>
<Route path="/contact-us" component={ContactUs}/>
<Route path="/" component={App}/>
</Switch>
</BrowserRouter>
Because you had given '/' as first route, anything would match it and render App component.
答案 1 :(得分:0)
我相信它匹配您的第一个路线App
,因为您没有指定它应该是exact
。
你可以这样做:
<Switch>
<Route exact path="/" component={App}/> // it will match only for '/'
<Route path="/about-us" component={AboutUs}/>
<Route path="/contact-us" component={ContactUs}/>
</Switch>