반응형
SMALL
1. npx create-react-app 으로 리엑트 설치하기
2. npm install mobx 로 몹엑스 설치하기
- countStore.js를 생성했다.
- class로 생성하라고 강의에서 알려줬다.
- 여러가지 기능이 있는거 같은데 observable이 공유할 녀석이다.
- computed 는 계산에 따른거, 여기서는 count의 상태에 따라 바뀔 것 인거 같다.
- action은 동작
- 나머지 잘 만들어주면 된다.
import { action, computed, makeObservable, observable } from "mobx";
export default class counterStore {
count = 0;
constructor() {
makeObservable(this, {
count: observable,
isNegative: computed,
increase: action,
decrease: action
})
}
get isNegative() {
return this.count < 0 ? 'Yes' : 'No';
}
increase() {
this.count += 1;
}
decrease() {
this.count -= 1;
}
}
- 사용하려면 최상위 index.js 건드려야 한다.
- 만들어놓은 counterStore 가져와서 store라는 이름의 인스턴스 만들어줬다.
- App 컴포넌트에 myCounter라는 이름으로 props를 통해 store를 내려줬다.
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import counterStore from './countStore';
const store = new counterStore();
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App myCounter={store}/>
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
3. npm install mobx-react 로 몹엑스리엑트 설치하기
- 대충 UI를 만들어줬다.
- 실제로 값이 변할 때 리렌더링 해주려면 mobx-react에서 observer 가져와서 App 컴포넌트를 감싸줘야한다.
- 필자는 기본으로 생성되어 있는 App.js를 안건드려서 그냥 function으로 생성 된 컴포넌트라서 맨아래 export 된 App을 observer로 감싸줬다.
- arrow function 이면 알아서 적당히들 감싸는 법은 알꺼라고 생각한다. 나는 솔직이 이번에 쓴 방법이 처음이다.
import logo from './logo.svg';
import './App.css';
import { observer } from 'mobx-react';
function App(props) {
const { myCounter } = props;
console.log('myCounter', myCounter);
return (
<div style={{ textAlign: 'center', padding: 16 }}>
카운트: {myCounter.count}
<br /><br />
마이너스?: {myCounter.isNegative}
<br /><br />
<button onClick={() => myCounter.increase()}>+</button>
<button onClick={() => myCounter.decrease()}>-</button>
</div>
);
}
export default observer(App);
반응형
LIST
'React.js > 상태관리' 카테고리의 다른 글
React에서 MobX 사용해보기 3(react context 사용해서 observable 공유하기 (0) | 2024.02.26 |
---|---|
React에서 mobx 사용해보기 2 (decorator) (0) | 2024.02.26 |
react redux 기초4(applyMiddleware, thunk) (0) | 2024.02.07 |
React Redux 기초3(Provider, useDispatch, useSelector) (0) | 2024.02.07 |
React Redux 기초 2 - reducer 여러개 쓰기(combineReducers) (1) | 2024.02.05 |