ReduxStudy(Actions)

이승훈·2022년 10월 25일
0

TIL

목록 보기
13/31
post-thumbnail

Actions

import { createStore } from "redux";

const add = document.getElementById('add');
const minus = document.getElementById('minus');
const number = document.querySelector('span');

const countModifier = (state = 0) => {
  return state;
};

const countStore = createStore(countModifier);

createStore 함수는 Store를 create한다.

store는 나의 data를 저장하는곳이다.

store를 만들면 만든 store(위의 코드에선 countStore가 되겠다.)에 reducer(countModifer)를 줘야한다.

default로 reducer(data modifier라고도한다.)는 현재의 state와 함께 불려진다.

위의 코드처럼 state의(reducer의 인자의) 초기값을 설정해주면 그것이 처음 initial state가 된다.

이 state를 action이라는것을 통해 수정할 수 있는것이다.

action은 reducer의 두번째 인자(argument)다.

action을 지정해 줄 수 있는 방법은 아래와같이 countStore에 dispatch 메소드를 사용하면 된다.

(action은 객체로만 지정이 가능하다.)

import { createStore } from "redux";

const add = document.getElementById('add');
const minus = document.getElementById('minus');
const number = document.querySelector('span');

const countModifier = (state = 0, action) => {
  console.log(action)
  return state;
};

const countStore = createStore(countModifier);

countStore.dispatch({type: "HELLO"})

위처럼 action을 지정해준 후 action을 콘솔창에서 출력해주면 아래와 같이 2번 출력이 된다.

countModifier가 2번 호출되었기 때문인데,

첫번째로는, initialized된 function으로 (initialized된 action으로)

두번째로, type이라는 다른 action과 함께

이다.

내가 store, dispatch, action을 지정해주면 redux가 reducer를 부를것이고

그형태는 아래와 같은 형태일것이다.

reducer(state = 초기값, { type: 내가 지정해준 action})   

이것이 내가 reducer 에게 명령을 보내는 방법이다.

자 그럼 아래같은 방식으로 reducer안에서 메시지를 받을 수 있겠다.

import { createStore } from "redux";

const add = document.getElementById('add');
const minus = document.getElementById('minus');
const number = document.querySelector('span');

const countModifier = (state = 0, action) => {
  if(action.type === "ADD") {
    console.log('더해라더해')
  }
  return state;
};

const countStore = createStore(countModifier);

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

알고있듯이 reducer가 return해주는 모든것은 data가 된다.

그렇다면 아래처럼 state를 수정해 줄 수있겠다.

import { createStore } from "redux";

const add = document.getElementById('add');
const minus = document.getElementById('minus');
const number = document.querySelector('span');

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

const countStore = createStore(countModifier);

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

console.log(countStore.getState())

자 이것이다.

리덕스는 이렇게 쏘씸플하다.

data의 store를 만들고(createStore(reducer)) message를 그 store에 전송하면 된다.

그리고 그 message를 store에 전송하는 방법으로는 dispatch를 사용하면 된다.

내가 전송한 message는 reducer안의 action에 담기게 된다.

profile
Beyond the wall

0개의 댓글