history push가 안되는 경우

:D ·2021년 12월 4일
3

Error 🤯

목록 보기
1/4

📌 react router dom v6 업데이트로 제가 해결방안으로 제시했던 방법이 사용못하게 되었습니다. 그전에 해결방안은 제가 해결했던 과정을 적어둔거라 지우는지는 않겠습니다. 더 아래로 내려서 글을 봐주세요!!

(2022.03.19에 글을 다시 수정하였습니다.)

history.push로 페이지를 넘기는 작업중이었다.
TypeError: Cannot read properties of undefined (reading 'push') 에러를 발견했고,
일단 this.props를 찍어보았다. 엥?!! history객체가 없더라.. 😅

이유는 무엇일까?

보통 App.js 에서 Route로 연결을 한다. 연결을 하게 되면 Router가 history api에 접근할 수 있게 되고 각 Route와 연결된 컴포넌트의 props로 match, location, history 객체를 기본적으로 전달하게 된다.

Route와 연결된 Home 컴포넌트의 Props를 확인해보니 다음과 같이 history, location, match 객체가 포함되어 있는 것을 확인할 수 있다.

에러는 Route 연결이 안되어있어서 발생했던것이었다. (그동안 어떤 경우에 발생했던것인지 못찾았다.😅 찾아서 다행이다.. ㅎㅎ)

import React from "react";
import { Route } from "react-router-dom";
import Home from "./Home";
import About from "./About"

function App() {
  return (
    <div>
      <Route path="/" exact={true} component={Home} />
      <Route path="/about" component={About} />
    </div>
  );
}

export default App;

해결 방안 : withRouter 사용

withRouter를 사용하면 라우터에 의해 호출된 컴포넌트가 아니더라도 history, location, match 객체에 접근할수 있도록 해준다.

withRouter를 적용하고 this.props를 찍어보니 history,location,match 객체가 생긴것을 볼 수 있고 에러도 해결되었다. 😊 👍

react router dom v6 업데이트로 withRouter가 사라졌습니다. 다른 해결방안!

https://reactrouter.com/docs/en/v6/getting-started/faq

React Router 공식문서에 잘 나와있습니다. 읽고 해보시면 모두 하실수 있을거예요👍!

profile
강지영입니...🐿️

0개의 댓글