오늘은 Redux에 대해서 알아보겠습니다. redux는 우리가 props를 전달 하거나 다른곳에서 데이터를 끓어서 가져올때
써야 할게 많잖아요??그걸 단순하게 해주는 거라고 생각하시면되요 즉 한번만 작성하면 어디서든 쓸수 있는 것들이죠
지역변수=props ,전역변수=redux 이렇게 이해해도 좋을거 같아요
그럼 npx creat-react-app 으로 해주시고 터미널 열어주세요
그리고 npm i redux 를 redux 설치해주세요
src/redux 폴더 만들어주시고 action.js reducer.js store.js 이렇게 만들어 줄께요
actions는 행동을 해서 정제되지 않은 데이터를 만들어 주는곳 이라고 생각하시면 되고
reducer는 action에서 데이터를 가져와서 정제된 데이터를 만들어 주는 것이다
store는 그 정제된 데이터를 저장해주느 것이라고 생각하시면 됩니다.
그럼 action.js부터 만들어보겠습니다.
export const ADD = "ADD";
export function add(index) {
return {
type: ADD,
index,
};
}
이렇게 작성해주세요
즉 type은 ADD이고 입력받은 변수를 전달해주겠다는 의미 입니다.
reducer.js 는
import { ADD } from "./action";
export default function fileReducer(previousState = [], action) {
if (action.type === ADD) {
return action.index;
}
}
작성
여기서 보면 action에서 ADD라는 변수를 가져와서 전달 받은 action의 type이 ADD랑 같으면 index를 전달해주겠다는 의미 입니다.
store.js
import { createStore } from "redux";
import fileReducer from "./reducer";
const store = createStore(fileReducer);
export default store;
작성
여기서 보면 reducer에서 전달 받은 것을 저장해주는 것입니다.
그리고 그걸 사용할수 있도록 export default 해주었습니다.
그럼 index.js가서 잘 되나 확인하겠습니다
그전에 npm star로 창을 켜주세요
index.js import모인곳 바로밑에
import store from "./redux/store";
import { add } from "./redux/action";
store.dispatch(add(5));
console.log(store.getState());
작성해주세요
console.log(store.getState()); 이걸로 안에 데이터가 있나 없나 확인하는 거고
store.dispatch(add(5)); 이걸로 데이터를 생성하는것입니다.
store.dispatch(추가할 내용) 이렇게 해서 5가 전달이 됩니다
const sub = store.subscribe(() => {
console.log(store.getState());
});
store.dispatch(add(5));
store.dispatch(add(5));
store.dispatch(add(5));
이렇게 내부 내용을 수정해보자
그리고 다시 npm start창을 보면
3개가찍혀있다 그리고 확인하는 것을 입력안했는데 자동으로 뜬다 즉 데이터의 변경이 있으면 계속 subscribe안에 있는 함수 내용을 실행시켜주는 것이다.
store.dispatch(add(5));
store.dispatch(add(5));
store.dispatch(add(5));
sub()
store.dispatch(add(5));
store.dispatch(add(5));
store.dispatch(add(5));
이렇게 입력해보자
이렇게 하고 콘솔을 보면
이렇게 똑같이 나온다.
즉 sub()가 나온 순간부터 함수 내부 내용을 실행 시키지 않는것이다
reducer.js
import { ADD } from "./action";
export default function fileReducer(previousState = [], action) {
if (action.type === ADD) {
previousState.push(action.index);
return previousState;
}
}
이렇게 변경 해주시면
기존 데이터에서 계속 index를 추가해서 배열로 다시 보내주기 때문에 데이터가 쌓이는것을 확인할수 있다.
action.js
export function subn(index) {
return {
type: SUB,
index,
};
이거 추가
이부분은 위에 랑 큰차이가 없으니 생략 하겠습니다.
reduce.js
if (action.type === SUB) {
return previousState.filter((p) => p !== action.index);
}
이거추가
여기는 전달받은 index값이랑 다른것만 다시 배열로 전달하겠다는 말입니다 즉 filter랑 같은 값들은 삭제하겠다는 의미가 됩니다.
index.js
import { add, subn } from "./redux/action";
const sub = store.subscribe(() => {
console.log(store.getState());
});
store.dispatch(add(5.1));
store.dispatch(add(5.2));
store.dispatch(add(5.3));
store.dispatch(subn(5.2));
이렇게 수정하시고 콘솔창을 보시면
데이터가 빠진것을 확인할수있습니다.
그럼이제 데이터를 유용하게 가독성 좋게 따로 작성해서 하나로 보내보겠습니다
redux 안에 add1 add2를 만들어주세요
reducer.js
import { combineReducers } from "redux";
import add1 from "./add1";
import add2 from "./add2";
const num = combineReducers({ add1, add2 });
export default num;
이렇게 수정
즉combineReducers로 두개를 하나로 묶어 객체로 내보내겠다는 의미입니다.
add1.js
import { ADD, SUB } from "./action";
export default function add1(previousState = [], action) {
if (action.type === ADD) {
previousState.push(action.index);
return previousState;
}
if (action.type === SUB) {
return previousState.filter((p) => p !== action.index);
}
return previousState;
}
add2.js
import { ADD2, SUB2 } from "./action";
export default function add2(previousState = [], action) {
if (action.type === ADD2) {
previousState.push(action.index);
return previousState;
}
if (action.type === SUB2) {
return previousState.filter((p) => p !== action.index);
}
return previousState;
}
이렇게 해서 두개의 reducer을 만들었습니다.
이제 action의 함수를 실행하면 두개가 동시에 실행되고 각자 코드대로 작동이 될것입니다.
즉 add함수가 실행되면 add1가서 배열에 index추가하고 add2는 충족되는 조건이 없으니까 그대로 예전데이터를 전달해 줄 것입니다.
action.js
export const ADD = "ADD";
export const SUB = "SUB";
export const ADD2 = "ADD2";
export const SUB2 = "SUB2";
export function add(index) {
return {
type: ADD,
index,
};
}
export function subn(index) {
return {
type: SUB,
index,
};
}
export function add2(index) {
return {
type: ADD2,
index,
};
}
export function subn2(index) {
return {
type: SUB2,
index,
};
}
이렇게 수정
index.js
import { add, subn, add2, subn2 } from "./redux/action";
const sub = store.subscribe(() => {
console.log(store.getState());
});
store.dispatch(add(5.1));
store.dispatch(add2(5.1));
store.dispatch(add(5.2));
store.dispatch(add2(5.2));
store.dispatch(add(5.3));
store.dispatch(add2(5.3));
store.dispatch(subn(5.1));
store.dispatch(subn2(5.1));
이렇게 수정
콘솔창을 보면
이렇게 객체로 제대로 전달이 되는것과 데이터가 잘 전달되는것이 확인이 됩니다.
이렇게 데이터를 생성하고 전달하느데 편하게 사용이 가능합니다.
오늘은 이까지 하고 내일 열심히 해봐요 ㅎㅎ