본 글은 노마더코더의 초보자를 위한 리덕스 101 강의를 들으며 작성한 글입니다.
더보기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<title>Vanilla Redux</title>
</head>
<body>
<button id="add">Add</button>
<span></span>
<button id="minus">minus</button>
</body>
</html>
Actions
import { createStore } from "redux";
const coountModifier = (count = 0, action) => {
return count;
};
const countStore = createStore(coountModifier);
redux에서 function을 부르기 위해 사용하는 2번째 파라미터이다. (첫번째 파라미터는 state)
reducer는 store에 저장된 파라미터를 업데이트하지만 +1을 할지 -1을 할지는 우리가 말해주어야한다.
이렇게 reducer에게 말할 수 있는 방법이 action이다.
dispatch
import { createStore } from "redux";
const coountModifier = (count = 0, action) => {
return count;
};
const countStore = createStore(coountModifier);
countStore.dispatch( {type: "HELLO"} );
그렇다면 reducer에 action을 보낼 방법을 알아야 보낼 수 있을 것이다.
이때 dispatch함수를 사용한다.
dispatch 함수의 매개변수는 객체로 type 속성을 필수적으로 가져야한다.
countStore.dispatch(...)에서 리덕스는 countMotifier(reducer)를 호출하고,
이 때 reducer에 ( currentState, { type : "HELLO" } )의 값이 들어간다.
이렇게 reducer에게 메세지를 보낼 수 있다.
import { createStore } from "redux";
const add = document.getElementById("add");
const minus = document.getElementById("minus");
const number = document.querySelector("span");
const ADD = "ADD";
const MINUS = "MINUS";
const coountModifier = (count = 0, action) => {
switch (action.type) {
case ADD:
return count + 1;
case MINUS:
return count - 1;
default:
return count;
}
};
const countStore = createStore(coountModifier);
add.addEventListener("click", () => countStore.dispatch({ type: ADD }));
minus.addEventListener("click", () => countStore.dispatch({ type: MINUS }));
다음과 같이 action과 switch 문을 통해 reducer에서 수행해야할 함수를 지정할 수 있다.
'Frontend > 상태관리' 카테고리의 다른 글
[React-Redux] mapDispatchProps (0) | 2022.01.14 |
---|---|
[React-Redux] connect, mapStateProps (0) | 2022.01.13 |
[Redux] NEVER MUTATE STATE (0) | 2022.01.13 |
[Redux] Subscribe (0) | 2022.01.13 |
[Redux] Store, Reducer (0) | 2022.01.12 |