React 상태 관리를 할 때 저는 Redux를 좋아하는데요,
한 번 구조를 정리해놓고 나중에 참고 해보려고 합니다.
간단히 디렉토리 구조를 먼저 보자면
/reducers
index.js
store.js
module1.js
module2.js
...
이런 느낌입니다~
index.js
import { bindActionCreators } from 'redux'; import store from './store'; const { dispatch } = store; /* append here */ export const TestReducer = bindActionCreators(require('./test'), dispatch); /* append here */
ducks 구조로 만든 모듈들을 하나씩 추가해나가는 구조입니다. 간단하죠?
store.js
// modules import { combineReducers } from 'redux'; import { penderReducer } from 'redux-pender'; // store import { createStore, applyMiddleware, } from 'redux'; import { createLogger } from 'redux-logger'; import penderMiddleware from 'redux-pender'; // modules const modules = combineReducers({ pender: penderReducer, /* append here */ test: require('./test').default, /* append here */ }); // store const store = (() => { const middleware = applyMiddleware(createLogger(), penderMiddleware()); return createStore(modules, middleware); })(); export default store;
index.js와 마찬가지로 ducks 구조로 만든 모듈들을 하나씩 추가해나가는 구조입니다. 그밖에 store를 만들면서 쓰고 싶은 미들웨어를 붙여주고 있고요,
저는 React 컴포넌트 외에서도 store를 쓰고 싶기 때문에 여기서 export를 해줍니다.
편의에 맞게 다음과 같이 적당~히 만들면 되겠죠?
test.js
import { createAction, handleActions } from 'redux-actions'; import { pender } from 'redux-pender'; import axios from 'axios'; import store from './store'; const initialState = { past: new Date(), now: new Date(), } const action = { setNow: 'test/setNow', } export const setNow = createAction(action.setNow, () => { const { test } = store.getState(); // console.log('test:', test); const promise = axios.get('/test'); return promise; }) export default handleActions({ ...pender({ type: action.setNow, onSuccess: (prevState, action) => { const { now } = prevState; const present = action.payload.data; const state = { ...prevState, past: now, now: present, }; return state; }, onFailure: (state, action) => { console.log('onFailure(): ', { state, action }); return state; } }), }, initialState);
평범한 ducks 구조입니다. Action 타입들을 UPPER_SNAKE_CASE
로 하지 않았는데.. 이유는 Reducer의 함수명과 동일하게 camelCase
로 표현하고 싶었습니다. 전체 검색에 잘 걸리도록이요.