티스토리 뷰

Node.js/react

Redux - Store

kkoon9 2020. 9. 27. 12:07

Store.js

import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const initalState = {};

const middleware = [thunk]; // [1].

const store = createStore( // [2]
  rootReducer, // [4]
  initalState,
  composeWithDevTools(applyMiddleware(...middleware)), // [3]
);

export default store;

 

[1]. thunk

2020/09/27 - [Node.js/react] - Middleware와 thunk

[2]. createStore

createStore(reducer, [preloadedState], [enhancer])

앱의 전체 상태 트리를 저장하는 Redex 저장소를 만드는 명령어.

한 프로젝트에는 오직 하나의 Store만 있어야 한다.

Arguments

  1. reducer (Function): 현재 상태 트리와 처리할 작업을 지정한 다음 상태 트리를 반환하는 축소 함수.
  2. [preloadedState] (any): The initial state. 앱에서 서버로부터 상태를 hydrate하거나 이전에 직렬화된 사용자 세션을 복원하기 위해 선택적으로 지정할 수 있다. combinedReducer와 함께 reducer를 만든 경우, 이는 전달된 키와 동일한 모양의 plain object여야 한다.
  3. [enhancer] (Function): The store enhancer. middleware, time travel, persistence 등과 같은 third-party 기능으로 store의 기능을 향상시키기 위해 사용한다. 오로지 applyMiddleware()를 사용한다.

Returns

(Store): 앱의 전체 State를 가지는 개체. state를 바꾸는 방법은 Action을 dispatch 해주는 방법 뿐이다.

[3]. applyMiddleware

applyMiddleware(...middleware) // middleware = [thunk]

Redex-thunk는 Action 생성자가 함수를 dispatch하여 컨트롤을 반전시킬 수 있도록 한다. 그들은 arguments로 dispatch를 받을 것이고 그것을 비동기적으로 부를 수도 있다. 그러한 기능을 thunk라고 부른다.

Arguments

  1. ...middleware (Function): Redex 미들웨어 API를 준수하는 기능. 각 미들웨어는 storedispatchgetState 기능을 명명된 인수로 받고, 함수를 반환한다. 그 함수는 다음 미들웨어의 dispatch 방식이 주어질 것이며, 잠재적으로 다른 주장으로 next(Action)을 호출하거나, 아니면 다른 시간에, 혹은 아예 호출하지 않는 행동 함수를 반환할 수 있다. 체인의 마지막 미들웨어는 다음 매개 변수로 실제 store의 디스패치 방식을 받아 체인이 종료된다. 그래서 미들웨어 서명은 ({getState, dispatch }} => next(Action)이다.

Returns

주어진 미들웨어를 응용한 Store enhancer. store enhancer signature은 createStore => createStore이지만 이를 적용하는 가장 쉬운 방법은 마지막 enhancer 인수로 createStore()에 전달하는 것이다.

[4]. rootReducer

import { combineReducers } from 'redux';
import alert from './alert';
import auth from './auth';
import profile from './profile';
import post from './post';

export default combineReducers({
  alert,
  auth,
  profile,
  post
});

복잡성을 줄이기 위해서 하나의 프로젝트에 하나의 스토어를 원칙으로 한다.

따라서 각 기능별로 만들어 둔 리듀서를 하나의 스토어로 합치기 위해 rootReducer를 만든다.



references

https://redux.js.org/introduction/getting-started

'Node.js > react' 카테고리의 다른 글

react-redux Flow  (0) 2020.09.28
Redux - connect  (0) 2020.09.28
Redux - Reducer, Action  (0) 2020.09.27
Middleware와 thunk  (0) 2020.09.27
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
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
글 보관함