자식컴포넌트에서 데이터에 변화가 있을 때, 부모컴포넌트의 state를 직접적으로 건드리지 않음
리덕스에서는 props drilling을 방지한다. (데이터를 필요한 컴포넌트로 바로 전달)
스토어: state 저장소
리듀서: state 수정소
1. 컴포넌트는 스토어에서 state를 구독한다.(스토어와 컴포넌트가 연결됐다.)
2. 어떤 컴포넌트에서 액션을 디스패치한다.(데이터를 바꾸려고 한다.)
3. 리듀서에서 스토어의 값을 변경한다.
4. 스토어는 구독한 컴포넌트들에게 상태가 변경되었음을 알린다.
5. 새로운 state를 받은 컴포넌트들은 리렌더링된다.
action: 바꾸고 싶은 데이터를 설명해 놓은 객체이다. 데이터를 바꿀 때 action(바꿀 데이터)을 디스패치한다.
actionCreator: action을 생성하는 함수이다. (액션 생성 틀)
reducer: action을 dispatch하면 자동으로 실행되는 함수,
switch문으로(경우의 수) 액션의 type (액션을 상황별로 분류한 이름) 마다 어떤 행동을 return 한다.
함수모음파일: (경로) src - redux - modules - bucket.js(덕스 모듈명)
1) action type
2) actionCreator
3) const initialState (리듀서의 state로 들어갈 변수, 필수는 아니다)
4) reducer
// bucket.js
//====================actionCreator 부분==================================
// Actions type
const CREATE = "bucket/CREATE";
const REMOVE = "bucket/REMOVE";
// Action Creators
export function createBucket(bucket) {
console.log("액션을 생성할거야");
return { type: CREATE, bucket };
}
export function removeBucket(bucket) {
return { type: REMOVE, bucket };
}
//====================reducer 부분==================================
const initialState = {
list: ["영화관 가기", "매일 책읽기", "수영 배우기", "해외여행가기"],
};
// Reducer
// state={} 는 state의 초기값이 {} (빈 딕셔너리) 라는 뜻이다. (오류를 방지한다. )
export default function reducer(state = initialState, action = {}) {
switch (action.type) {
case "bucket/CREATE": {
const new_bucket_list = [...state.list, action.bucket];
return { list: new_bucket_list };
}
case "bucket/REMOVE": {
const remove_bucket_list = state.list.filter(
(element) => !element.includes(action.bucket)
);
return { list: remove_bucket_list };
}
default:
return state;
}
}
스토어 생성파일: (경로) src - redux - configStore.js (스토어명)
1) const= rootReducer: 리듀서들을 모은다.
2) 스토어에 필요한 함수가 있다면 모은다.
3) const= createStore : state 저장소를 만든다.
import { createStore, combineReducers } from "redux";
import bucket from "./modules/bucket";
const rootReducer = combineReducers({ bucket });
//여러 개 합칠 때는? const rootReducer = combineReducers({bucket1, bucket2, bucket3, ....})
const store = createStore(rootReducer);
export default store;