Reducer는 2가지 Parameter를 갖음.
- 1st parameter: Default / Initial / Current State
- 2nd parameter: State에 변화를 줄 Action
const reducer = (state = 0, action) => {};
Reducer에 Action을 보내려면 Dispatch 함수를 사용하여야 함.
Action은 Object 형태여야 하며, type property가 필요함.
store.dispatch({ type: "HELLO" });
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 기본 개념
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