🚨🚨🚨
기본적인 리덕스의 작동 방식과 기능을 배우기 위해 리덕스 툴킷을 사용하기 전,
createStore()라는 함수를 사용하여 리덕스 저장소라는 걸 생성하여 개념을 학습 할 예정
ㅤ
( 리액트 리덕스 팀은 리덕스 툴킷이라는 추가 패키지와 리덕스 스토어를 생성하는 다른 방법을 사용할 것을 권장)
빈 폴더에 js파일 하나 만들기
node.js 패키지 생성
npm init -y
npm i redux

const redux = require("redux");
const store = redux.createStore();
const counterReducer = (state, action) => {
return {
counter: state.counter + 1
};
};
counterReducer()를 넣어서 createStore()를 만든다.const store = redux.createStore(counterReducer);
getState()는 createStore()로 생성된 저장소에서 사용할 수 있는 메소드counterSubscriber()함수가 변경될 때마다 트리거가 됨, 그래서 트리거가 될 때마다 getState() 메소드로 변경된 후의 최신 상태를 받을 수 있다.const counterSubscriber = () => {
const latestState = store.getState();
console.log(latestState);
};
counterSubscriber()함수를 인식하도록 하고 상태가 변경될 때마다 counterSubscriber()를 실행하도록 하기subscribe()메서드는 counterSubscriber()함수를 받고, Redux는 데이터와 저장소가 변경될 때마다 받은 함수 실행store.subscribe(counterSubscriber);
Cannot read properties of undefined (reading 'counter') 에러가 남.state파라미터에 default 파라미터를 주어야함//터미널
node redux-demo.js
const counterReducer = (state = { counter: 0 }, action) => {
return {
counter: state.counter + 1,
};
};
dispath()는 Action을 발송하는 메서드()store.dispatch({ type: "increment" });
dispatch()로 새로운 액션을 발송해서 Reducer함수를 다시 실행시켜서 다시 counter를 증가해서 2라는 결과 출력
발송하고 있는 타입의 액션은 전혀 효과가 없음 (아래 글을 통해 자세히 살펴보기)
일반적으로 Redux를 사용할 때 Reducer 내부에서 다른 액션은 다른 일을 하는 게 목표이다. 따라서 Reducer 함수 파라미터에 두번째 인자로 action이 있는 것임
현재 상태를 받고 디스패치 된 액션을 받으면 그게 Reducer를 돌아가게 함
Reducer 내부에서 action 확인
1출력const counterReducer = (state = { counter: 0 }, action) => {
if (action.type === "increment") {
return {
counter: state.counter + 1,
};
}
return state;
};
store.dispatch({ type: "decrement" });를 통해 상태를 또 바꿈0이 됨
const counterReducer = (state = { counter: 0 }, action) => {
if (action.type === "increment") {
return {
counter: state.counter + 1,
};
}
if (action.type === "decrement") {
return {
counter: state.counter - 1,
};
}
return state;
};
.
.
생략
.
.
store.dispatch({ type: "increment" });
store.dispatch({ type: "decrement" });
