Cannot read property ‘location’ of undefined 에러

Updated:

router Error문제

Q :(

Cannot read property 'location' of undefined 라는 에러가 나오는 현상이 나왔다.

기존 작성한 코드

import React, { Component } from "react";
import { BrowserRouter as Route, Router, Switch } from "react-router-dom";
import Home from "./components/Home";
import About from "./components/About";
import Contact from "./components/Contact";
import NoMatch from "./components/NoMatch";

class App extends Component {
  render() {
    return (
      <Router>
        <Switch>
          <Route path="/" exact component={Home}></Route>
          <Route path="about" component={About}></Route>
          <Route path="contact" component={Contact}></Route>
          <Route path="nomatch" component={NoMatch}></Route>
        </Switch>
      </Router>
    );
  }
}
export default App;

A :) 해결방법 stackoverflow ⇒ https://stackoverflow.com/questions/43159975/cannot-read-property-location-of-undefined?rq=1


import React from 'react';
import { Router, Switch, Route} from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';

const history = createBrowserHistory();

ReactDOM.render(
    <Router history={history}>
        <Switch>
            <Route path='/' component={App}/>
        </Switch>
    </Router>,
     document.getElementById('root')
    );
  • 라우터의 버전이 올라감에 따라 변화가 일어난 거 같다. 스택오버플로를 참조하여 해결
  • 기존에 {BrowserRouter as Route, Router, Switch} 에서 “BrowserRouter” 를 제거하고 import createBrowserHistory from 'history/createBrowserHistory' 와 기존라우터에 history를 추가하여 화면에 나타나게 만들었다!