Basic Redux의 기본

Jeongho Heo·2019년 7월 4일
3

Redux

목록 보기
1/3


Redux는 기본적으로 React뿐만 아니라 다양한곳에서 사용될수있다.
특히 React에서 상태관리를 할때 Redux를 사용하면 좋다.

  • Action(액션)

    Action은 Store라는 저장소에 정보를 전달하기 위한 데이터 묶음이다.

Ex)

const ADD_TODO = 'ADD_TODO'
 { 
    type: ADD_TODO, 
    text: 'Build my first Redux app'
 }
  • Action Creator(액션 생성자)

    Action Creator는 단지 Action을 만들기 위한 함수다.

Ex)

const AddTodo = (text) => {
	type: ADD_TODO,
    text
}
  • Reducer(리듀서)

Reducer들은 각각의 상태변화를 어떻게 시킬지 관리해주는 정보가 담겨져 있다.이들은 전부 Store와 정보를 주고받는 역할을 한다.

Reducer는 그안에서 애플리케이션에 어떤 변화가 생긴다면 전달된 Action을 보고 어떻게 state를 교체시킬지 관리해주는 역할을한다.

Ex)

// reducer의 상태를 초기화 해주는 역할이다.

const todos = (state = [], action) => {
  // Action의 타입을 보고 어떻게 state를 교체해줄지 결정해준다.
  switch (action.type) {
  case ADD_TODO:
    /* 
    아래와 같이 Return해주는 이유는 원래 존재했던 Todo목록을 그대로
    불러온 후 추가적으로 ToDo를 추가해준다.	
    */
    return [...state, {
      text: action.text,
      completed: false
    }];
  case COMPLETE_TODO:
    return [
      ...state.slice(0, action.index),
      Object.assign({}, state[action.index], {
        completed: true
      }),
      ...state.slice(action.index + 1)
    ];
  // 어떤 경우도 통과되지 못하면 원래 존재했던 state를 반환한다.
  default:
    return state;
  }
}
  • CombineReducers

    CombineReducers는 많은 Reducer들을 하나로 합쳐 하나의
    Reducer로 관리할수 있게 만들어준다.

Ex)

import { combineReducers } from 'redux';

const todoApp = combineReducers({
  visibilityFilter,
  todos
});
  • Store(스토어)

    Store는 앱의 전체 상태를 저장하고있는 창고이다.

CreateStore

createStore는 Store를 만들어주는 역할을 해준다.

import { createStore } from 'redux';
import todoApp from './reducers';

// Reducer들을 store안에 넣어주어서 서로 연결해준다.
let store = createStore(todoApp);

getState

getState는 store안의 상태를 가져와준다.

// Store의 상태를 확인하기 위해 console에 찍어본다.
console.log(store.getState());

dispatch(action)

스토어에 있는 reducer들에게 action을 전달해준다.
각각의 reducer들은 자신에게 맞는 action이 들어온다면 store의
상태를 교체 할것이다.

store.dispatch(addTodo('Learn about actions'));
profile
풀스택을 지향하고 프론트엔드 개발을 좋아하는 프론트엔드 개발자 입니다.

0개의 댓글