Redux_ 시작하기

Adela·2020년 11월 16일
0

Redux

목록 보기
1/2
post-thumbnail

React와 많이 사용하는 것일 뿐, React의 라이브러리가 아니라 JavaScript 언어와 함께 사용할 수 있다.

시작하기

npm i redux

용어와 간단한 사용법

Store : data, state

store는 어플리케이션 내에 변화가 있는 데이터를 저장하는 곳이다.

import { createStore } from "redux";

const store = createStore(reducer);
// 변수명이 꼭 store일 필요없다.

createStore함수는 reducer함수를 인자로 받는다.
reducer함수가 리턴하는 값이 store에 있는 state를 변경한 값이 된다.

const stateModyfier = () => {
  // reducer함수로 쓰일 함수
  return "Hello";
}

const store = createStore(stateModyfier)

console.log(store);
/* dispatch, subscribe, getState,...
 store에 있는 데이터에 접근하려면 getState를 사용한다. */
store.getState();  // Hello 출력

Reducer : function (modifies data)

data를 변경하고 싶을 때 사용한다.
초기 상태값을 인자로 갖고, 그 값을 변경하기 위한 로직을 작성한다.

Reducer의 반환값이 중요한데, Reducer가 return하는 값이 어플리케이션의 data(state)가 된다.

const reducer = (initialState = [], action) => {
  console.log(initialState, action);
  // [] {type: "@@redux/INITy.f.4.n.p"}
  // 초기값[]과 action이 위처럼 찍힌다.
  return initialState;
}
// 변수명이 꼭 reducer, initialState, action일 필요없다.

⚡️ Reducer만 state값을 변경할 수 있다.⚡️
Reducer 함수를 구성하는 두번째 인자 Action으로 Reducer함수를 제어하여 state를 변경하는 것이다.

Action : communicate to Reducer

Reducer에 Action을 보내려면 store.dispatch({type: @@@})로 보낼 수 있다.
Action은 plain Object여야 한다. type도 꼭 가져야 하는 key이름이다.

store.dispatch({ type: "Hi" });

Store의 dispatch로 Action을 보내면 Reducer가 호출된다.

const reducer = (currState = "", { type: "Hi" }) => {
}

이렇게 Reducer의 두번째 인자 Action으로 들어가 호출되는 것이다.

const reducer = (currState = "", action) => {
  console.log(action.type);  // "Hi"
  switch(action.type){
    case "Hi":
      return currState + "!!!";
    case "Hello":
      return currState + "???";
    default:
      return currState;
  }
}

console.log(store.getState());  // 위의 Reducer로 변경한 값 확인

reducer내에서 action.type으로 값에 따라 로직을 작성해서 원하는 변화를 만든다.

상태를 변경할 수 있는 것은 오직 Reducer 뿐이다.

store에 변화가 있으면 변화를 감지하고 실행되는 함수가 있다.

Subscribe : change listener

action을 호출하는 store의 dispatch
store의 변화를 감지하는 subscribe

변화가 생길 때마다 어떤 함수를 실행하고 싶다면 아래와 같이 호출하면 된다.

const onChangeListener = () => console.log("Changed!!!");

store.subscribe(onChangeListener);

getState()를 함께 사용하여 값이 변하면 변화된 현재의 값을 읽을 수 있다.

// 버튼에 적힌 텍스트가 변경되는 값으로 바뀌는 예제

const btn = document.querySelector("button");
const getCurrentState = () => {
  btn.innerText = store.getState();
}

store.subscribe(getCurrentState);
profile
👩🏼‍💻 SWE (FE) 🚀 Be GRIT!

0개의 댓글