我有此代码,我一直在努力上班。无法找出问题所在!没有错误,我尝试了几种导入/导出方法,并将函数更改为const。
import React, { Component } from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import { Home } from "./Home";
import { Contact } from "./Contact";
class App extends Component {
render() {
return (
<React.Fragment>
<Router>
<Switch>
<Route path="/" component={Home} />
<Route path="/contact">
<Contact />
</Route>
</Switch>
</Router>
</React.Fragment>
);
}
}
export default App;
Then I have two separate functions
import React from "react";
export function Home() {
return (
<div>
<h2>Whats up!</h2>
<p>This is sample text. </p>
</div>
);
}
import React from "react";
export function Contact() {
return (
<div>
<h2>Contact page!</h2>
<p>This is different text. </p>
</div>
);
}
export default Contact;
根据您的最后一条评论-“以上代码实际上显示的是第一条路线中的任何内容,无论网址如何”,问题是您没有为Route
组件提供exact
的true
属性。
Switch
将呈现第一个匹配的Route
,并跳过所有其他匹配项。由于/
“匹配”所有路由,因此您只会看到Home
组件。