[Redux] JavaScript with Redux

Janet·2022년 10월 13일
0

Redux

목록 보기
2/3

🔶 Redux에서 사용하는 기본적인 함수

  • createStore: Store를 생성하는 함수.
  • Store: Application에서 바뀌는 Data(State)를 넣는 곳.
  • Reducer: Data(State)를 modify해주는 함수. Reducer가 return하는 것은 App에 있는 Data가 됨.
    • Reducer는 2가지 Parameter를 갖음.
      - 1st parameter: Default / Initial / Current State
      - 2nd parameter: State에 변화를 줄 Action

      const reducer = (state = 0, action) => {};
  • Action: Store를 수정할 수 있는 유일한 방법은 Action을 보내는 것.
    • Reducer에 Action을 보내려면 Dispatch 함수를 사용하여야 함.

    • Action은 Object 형태여야 하며, type property가 필요함.

       store.dispatch({ type: "HELLO" });
  • Redux에서는 Data의 변경/수정을 원할 경우, Mutate(변형)하지 않고 새로운 Objects, 즉 새로운 State를 return하는 방식으로 Data의 변경이 이뤄져야 함.
    • Mutate State 예시

      const numbers = ["1", "2"];
      numbers.push("3");
      console.log(numbers); // (3) ['1', '2', '3']
    • Add a new object 예시

      const reducer = (state = [], action) => {
      	return [...state, { text: action.text }];
      };

🔶 Redux with Vanilla JavaScript

1. Code로 보는 Redux 기본 개념 & 활용

//Redux 기본 개념

import { createStore } from "redux";
//redux에는 createStore 함수가 있음
//createStore는 Store를 생성하는 함수
//Store: state(app에서 바뀌는 data)를 넣는 곳

const reducer = (state = 0, action) => {
	console.log(action); //{type: 'HELLO'}
	return state;
};
//reducer는 data를 modify해주는 함수로 reducer가 return하는 것은 app에 있는 data가 됨.
//reducer 1st parameter: default(initial) state, 여기선, default state = 0
//reducer 2nd parameter: state에 변화를 줄 action이 들어간다.
//action: redux에서 function을 부를때 쓰는 2번째 인자로 이를 통해 data를 modify할 수 있음.

const store = createStore(reducer);
//createStore 함수는 reducer가 필요.

store.dispatch({ type: "HELLO" });
//reducer에 action을 보내는 방법으로 store에 dispatch 함수를 사용.
//action은 object 형태여야하며, type이 필요함.
//Redux 활용

import { legacy_createStore } from "redux";

const countModifier = (count = 0, action) => {
  if (action.type === "ADD") {
    return count + 1;
  } else if (action.type === "MINUS") {
    return count - 1;
  } else {
    return count;
  }
};

const countStore = legacy_createStore(countModifier);

countStore.dispatch({ type: "ADD" });
countStore.dispatch({ type: "ADD" });
countStore.dispatch({ type: "ADD" });
countStore.dispatch({ type: "ADD" });
countStore.dispatch({ type: "ADD" });
countStore.dispatch({ type: "MINUS" });

console.log(countStore.getState()); //4
profile
😸

0개의 댓글