反应路由器:需要

React Router: need

我有这段代码,我一直在尝试开始工作。无法弄清楚它有什么问题!没有错误,我已经尝试了 importing/exporting 的几种方法,并将函数更改为 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;

根据您最后的评论 - "The above code actually displays whatever is in the first Route no matter the url",问题是您没有为 Route 组件提供 trueexact 道具。

Switch 将呈现第一个匹配项 Route 并跳过所有其他匹配项。由于 / "matches" 所有路由,您只能看到 Home 组件。