react-router v4  browserHistory.push 오류 해결 방법


리엑트 라우터가 버전3에서 버전4로 올라감에 따라 


엄청나게 많은 것들이 변했다.


지금 새로운 프로젝트를 만들고 새로운 버전의


패키지들을 받은 후 코딩을 하려면 불과 한달전에 공부했던 코드들이 동작하지 않게 되었다.



망할.. 예전 webpack 버전1에서 2버전으로 올라가면서 바뀐거 찾아내느라 생고생 했는데



이젠 react-router가 문제다




Link를 사용하지 않고 바로 함수 내에서 리다이렉트를 시키는 방법으로


v3에서는 



1
browserHistory.push('/');
cs


이렇게 사용 하였으나


v4에선


Uncaught (in promise) ReferenceError: browserHistory is not defined


브라우저 콘솔창에 위와 같은 에러 메세지가 나타난다.


해결방법


생각보다 간단했다. 위의 코드 대신에


1
this.props.history.push('/');
cs



이렇게 사용해주면 된다.


물론 상단에 리엑트 라우터를 임포트시킬 필요는 없다.


그냥 기능이 넘어와 버린건지 정확하게는 알 수 없지만


깃터브를 뒤져보니 아래와 같은 의견을 찾았다.


걍 이전버전에서는 됐는데 v4에선 안된다 라는 말 같다.





@wyze @timdorr first of all thanks for the v4. I have a few questions and I could not find any solutions for this anywhere, so asking here.

In the earlier versions of the react-router, we could push the the URL using browserHistroy.push() method. When you use browserHistroy the query which you pass, will be transformed to the search key in the history object. The below is an example which used to work in earlier versions.

let query = {
  reportType: 'summary',
  timeZone: 'UTC'
}
  browserHistroy.push({
    pathname: 'some_path',
    query
  })

This will resolve the URL to - test.com/some_path/?reportType=summary&timeZone=UTC

In the current version (v4), it is not possible to pass the query object to the history.push() method.

  histroy.push({
    pathname: 'some_path',
    query
  })

This will resolve the URL to - test.com/some_path/

How to get this working with v4.

module not found error cannot resolve 'babel' in 에러와 the node api for babel has been moved to babel-core  해결 방법




드디어 리액트에 입문!


아직 뭐가 뭔지도 잘 모르고


바벨이라는 녀석이 ES6문법으로 바꿔주고 웹팩이라는 녀석이 번들js로 


관리해준다는 대략적인 정보만 알고 난 상태에서


https://velopert.com/814


이분의 강좌를 보면서 공부를 하기로 시작 했는데 시작과 동시에 에러가 날 반겨준다.




1. the node api for babel has been moved to babel-core  해결 방법




<으아악 불길한 붉은 텍스트라니>



the node api for babel has been moved to babel-core


이 에러는 뭐 대충 설치 할때 경로 문제나 디펜던시 설정 문제 인듯 하다


pakage.json 파일의 디펜던시를 아래와 같이 바꿔주면 해결이 된다.


아마 위의 에러가 나는 것은 딘펜던시와 덴펜던시스 둘다 바벨이 들어가 있는 경우이며


글로벌로 babel과 webpack를 설치 한 후


또 종속성으로 --save 명령어로 설치하는 경우에 나타나는 에러 인듯 하다.



1
2
3
4
5
6
7
8
9
10
11
12
 "dependencies": {
    "react": "^15.4.2",
    "react-dom": "^15.4.2"
  },
  "devDependencies": {
    "babel-core": "^6.23.1",
    "babel-loader": "^6.3.2",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-react": "^6.23.0",
    "webpack": "^2.2.1",
    "webpack-dev-server": "^2.4.1"
  }
cs


디펜던시 목록을 위와같이 수정해주면 사라지며


그래도 계속 나타날 경우엔 어차피 튜토리얼 단계니까 


폴더 지우고 다시 순서대로 받아주면 해결 된다.




2.module not found error cannot resolve 'babel' in 에러 해결 방법





이 에러는 webpack.config.js 파일을 수정해 주어야 한다.


이 파일은 webpack의 설정파일인데


ECMAScript6를 컴파일 해주고 개발서버를 열어주는 webpack의 설정 파일인데


모듈 로더 부분이


1
2
3
4
5
6
7
8
9
10
11
12
13
    module: {
        loaders: [
            {
                test: /\.js$/,
                loader: 'babel',
                exclude: /node_modules/,
                query: {
                    cacheDirectory: true,
                    presets: ['es2015''react']
                }
            }
        ]
    }
cs



이런식으로 loader:'babel'

로 되어있는 경우 발생한다


바벨을 참조하지 못해서 생기는 오류인듯 한


loader:'babel' -> loader:'babel-loader' 이렇게 바꿔주면 간단히 해결이 된다.


1
2
3
4
5
6
7
8
9
10
11
12
13
   module: {
        loaders: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    cacheDirectory: true,
                    presets: ['es2015''react']
                }
            }
        ]
    }
cs



이제 npm start 명령어를 실행하면 complied successfully 라는 반가운 문구를 볼 수가 있게 된다.



+ Recent posts