简体   繁体   English

React-Router 路由到类组件

[英]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.我是使用 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索引.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应用程序.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探索.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.这工作正常,您所要做的就是将/explore/one添加到 url 以查看路由是否正常工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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