Javascript의 React-Router withRouter란

JavaScript 공부 노트

Posted by 쭌프로 on January 18, 2019

Recently by the same author:


Spring Security Filter Bean 주입받기

Spring Security Filter Bean 주입받기

You may find interesting:


ReactJS 초기 환경 설정

ReactJS 개발전 초기 환경 설정


Javascript의 ReactJS-TimeAgo IE 개체인식 오류 해결

JavaScript 공부 노트

React-Router 의 withRouter 관련글을 쓰는 이유

React 공부를 학원을 안다니고 옛날 인강 && 블로그 자료로 독학을 하다보니 최신 업데이트 자료가 아닌 구버전 자료로 지식을 습득했습니다.

그러다 보니 블로그 예제대로 실행을 해보면 빈번하게 오류가 나서 그 부분만 구글링 && stack overflow 직접찾아 버전을 업그레이드 하고 다시 적용 시키면서 독학을 하고있습니다.

이번에 블로그 예제를 보면서 작업하는 도중

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import React from 'react';
import { Route } from "react-router-dom";
import { Header } from '../components';
 
class App extends React.Component {
    render() {
 
        let re = /(login|register)/;
        let isAuth = re.test(this.props.location.pathname);
 
        return (
            <div>
                {isAuth ? undefined : <Header/>}
            </div>
        );
    }
}
 
export default App;
cs

이부분에서 해당 링크의 pathname 을 가져와 조건문으로 비교해야하는 부분이 있었습니다.

이부분을 최신버전(React-Router-v4) 버전으로 적용하여 실행하면 pathname 을 찾을 수 없다는 문구가 나옵니다.

자바스크립트 출력확인

구글링을 찾아본 결과

stack overflow 의 질문글을 보고 아하! React-Router-4 버전 이후부터는 withRouter 사용하여 가져와야 하는구나 했습니다.

바로 React-Router 홈페이지로 접속하여 React-Router-4 버전의 withRouter란 무엇인지 그리고 사용방법을 보고 오류나는 부분을 수정했습니다.

withRouter 고차원 컴포넌트 란?

withRouter 고차원 컴포넌트를 통해 history 객체의 속성과 가장 가까운 의 match 액세스 할 수 있습니다.</p>

withRouter는 render props : { match, location, history } 와 같은 props로써 경로가 변경 될 때마다 해당 구성 요소를 다시 렌더링합니다.</p>

withRouter는 주로 history에 접근하여 컴포넌트에서 라우터를 조작하는 데 사용합니다.

</div>

withRouter 를 추가하여 location.pathname 을 출력해 보겠습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import React from 'react';
import { Route, withRouter } from "react-router-dom";    // withRouter 를 추가
import { Header } from '../components';
 
class App extends React.Component {
    render() {
 
        let re = /(login|register)/;
        let isAuth = re.test(this.props.location.pathname);
 
        return (
            <div>
                {isAuth ? undefined : <Header/>}
                {this.props.location.pathname} // 정상적으로 pathname 을 출력하는것을 확인할 수 있습니다.
            </div>
        );
    }
}
 
export default withRouter(App);    // withRouter 를 추가
cs

정상적으로 location.pathname 을 출력하는 것을 확인할 수 있습니다.

withRouter 외에도 여러가지 2-3버전과 4 버전이 다르므로 꼭 확인하며 프로그래밍 하는것이 좋습니다.

독학이란 넘모 어려운것..