为什么我总是收到带有React Router的错误消息

时间:2020-05-04 06:55:16

标签: reactjs react-router

每次我运行npm start都会给我一条错误消息:

错误:元素类型无效:预期为字符串(对于内置组件)或类/函数(对于复合组件),但得到了:对象。您可能忘记了从定义文件中导出组件,或者可能混淆了默认导入和命名导入

import React, { Component } from "react";
import {
    Route,
    NavLink,
    HashRouter
  } from "react-router-dom";
  import Home from "./containers/Home";
  import About from "./containers/About";
  import Resume from "./containers/Resume";
 
class Main extends Component {
  render() {
    return (
        <HashRouter>
        <div>
          <h1>Simple SPA</h1>
          <ul className="header">
            <li><NavLink to="/">Home</NavLink></li>
            <li><NavLink to="/about">About</NavLink></li>
            <li><NavLink to="/resume">Resume</NavLink></li>
          </ul>
          <div className="content">
            <Route path="/" component={Home}/>
            <Route path="/about" component={About}/>
            <Route path="/resume" component={Resume}/>
             
          </div>
        </div>
        </HashRouter>
    );
  }
}
 
export default Main;

import React from "react";
import ReactDOM from "react-dom";
import Main from "./Main";
 
ReactDOM.render(
  <Main/>, 
  document.getElementById("root")
);

import React, { Component } from "react";
 
class Home extends Component {
  render() {
    return (
      <div>
        <h2>HELLO</h2>
      </div>
    );
  }
}
 
export default Home;

1 个答案:

答案 0 :(得分:0)

嗨,在这里工作正常。请检查以下示例:

import React, {useState} from 'react';
import {BrowserRouter as Router, HashRouter, Link, NavLink, Route, Switch} from "react-router-dom";

class App extends React.Component {
    render() {
        return (
            <HashRouter>
                <div>
                    <h1>Simple SPA</h1>
                    <ul className="header">
                        <li><NavLink to="/">Home</NavLink></li>
                        <li><NavLink to="/about">About</NavLink></li>
                        <li><NavLink to="/resume">Resume</NavLink></li>
                    </ul>
                    <div className="content">
                        <Route path="/" component={Home}/>
                        <Route path="/about" component={About}/>
                        <Route path="/resume" component={Resume}/>
                    </div>
                </div>
            </HashRouter>
        )
    }
}
export default App;

class Home extends React.Component {
  render() {
    return (
      <div>
        <h2>HELLO</h2>
      </div>
    );
  }
}

class About extends React.Component {
  render() {
    return (
      <div>
        <h2>About</h2>
      </div>
    );
  }
}

class Resume extends React.Component {
  render() {
    return (
      <div>
        <h2>Resume</h2>
      </div>
    );
  }
}