简体   繁体   中英

TypeError: Cannot read property 'location' of undefined in react

提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供   中文简体   中文繁体   中英对照 版本,有任何建议请联系yoyou2525@163.com。

I am creating a simple React application, and while implementing Routing I get following error:

TypeError: Cannot read property 'location' of undefined in react.

App.js:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Header from "./components/header";
import Home from "./components/Home";
import About from "./components/About";
import Contact from "./components/Contact";
import { Router, Route} from 'react-router'

class App extends Component {
  render() {
    return (
      <div className="App">
      <Header />

   <Router>
      <Route path = "/" component = {App}>
         <Route path = "home" component = {Home} />
         <Route path = "about" component = {About} />
         <Route path = "contact" component = {Contact} />
      </Route>
   </Router>
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>

            Edit <code>src/App.js</code> and save to reload.
          </p>
          <a  className="App-link"  href="https://reactjs.org"target="_blank"  rel="noopener noreferrer">
            Learn React
          </a>
        </header>
      </div>
    );
  }
}

export default App;

What am I missing here?

1 anwsers

The problem here seems to be with import of router package.

install: npm install --save react-router-dom

Import the package in your App.js as:

import { BrowserRouter, Route } from "react-router-dom";

And now modify your App.js render() function as-

 return (
  <BrowserRouter>
      <div className="App">
      <Header />

        <Route exact path = "/" component = {Home} />
        <Route path = "about" component = {About} />
        <Route path = "contact" component = {Contact} />


      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>

          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a  className="App-link"  href="https://reactjs.org"target="_blank"  rel="noopener noreferrer">
          Learn React
        </a>
      </header>
    </div>
  </BrowserRouter>
);
暂无
暂无

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-2022 STACKOOM.COM