티스토리 뷰

React

:create-react-app 에서 mobx 사용하는방법(+오류해결)


| 순서
  • create-react-app으로리액트 프로젝트를 만든다.
  • yarn eject로 eject를 한다.
  • npm install --save mobx mobx-react
  • 컴포넌트 구성

#App.js


import React, {Component} from 'react';

import {observer} from 'mobx-react';
import Devtools from "mobx-react-devtools";

@observer class App extends Component {
render() {
return (
<div>
<Devtools/>
Counter{this.props.store.count}<br/>
<button onClick={this.handleInc}>+</button>
<button onClick={this.handleDec}>-</button>
</div>)
}
handleDec=()=>{
this.props.store.decrement();
}
handleInc=()=>{
this.props.store.increment();
}
}
export default App;


#index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import appState from './store/AppState';


ReactDOM.render(<App store = {appState}/>, document.getElementById('root'));


#Appstate.js

import { observable,action } from 'mobx';

const appState=observable({
count:0
})
appState.increment=function(){
this.count++;
}
appState.decrement=function(){
this.count--;
}

export default appState;


create-react-app 에서는 mobx 를 쓰려하면 syntax 오류가 난다. 이를 해결할 방법을 아래에서 확인해보자.


| 발생하는 오류

  • @ 로 쓰는 decorator 문법 syntax error가 나는것인데, 이를 create-react-app 이 지원을 안해주기 때문이다.


| 해결방법


https://stackoverflow.com/questions/41138534/mobx-react-unexpected-token%20%EC%B0%B8%EA%B3%A0  참고

  • 아래 내용을 package.json부분babel 부분에 추가해줘서 decorator 문법을 사용해 오류를 해결해준다.

추가할 내용

#package.json

"plugins": [
"transform-decorators-legacy"
],


추가후

#package.json

"babel": {
"plugins": [
"transform-decorators-legacy"
],
"presets": [
"react-app"
]
},


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
TAG
more
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함