简体   繁体   中英

React-Router routing to class components

I am trying to route to a class component but it gives me an error. When I change the component to a functional component, the routing works. How do I route to class components?

I am new to using react-router. I first had a functional component to route to. But once I realized the component needs to be a class, I changed it to a class and now the routing shows

"Cannot GET /explore/words'.

index.js

import React from "react";
import { render } from "react-dom";
import { BrowserRouter } from "react-router-dom";
import App from "./App";

render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.querySelector("#root")
);

App.js

import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";

import HomePage from "./pages/HomePage";
import ExplorePage from "./pages/ExplorePage";

function App() {
  return (
    <Router>
    <div>
      <header>
        <nav>Course Finder</nav>
      </header>
        <Route path="/" component={HomePage} />
        <Route path="/explore/:campus" component={ExplorePage} />
    </div>
    </Router>
  );
}

export default App;

Explore.js

import React, { Component } from "react";

class ExplorePage extends Component {
  render() {
    return (
      <div>
        <h1>Explore</h1>
      </div>
    );
  }
}

export default ExplorePage;

Expected result was to see the 'Explore' heading. I get 'Cannot GET /explore/words' instead.

This is working fine, all you have to do is add /explore/one to url to see the route working.

https://codesandbox.io/embed/nervous-wood-cw8cd

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM