기본 콘텐츠로 건너뛰기

Redux + React

Redux + React

Redux는 state 관리 툴이다. 오해하지 말아야할 것이, React에 의존하지 않는 툴이다. Vue, Angular 심지어 vinilla JS에서도 돌아간다. 그러나 React에서 사용하면서 유명세를 탄 것도 사실이므로 React와 Redux를 같이 배우는 것이 좋다. 우선 기본적인 Redux를 살펴보고 이후에 React에 적용해보도록 하자.

🚗 redux 설치

npm i redux

🚗 Reducer

Context API와 마찬가지로 Store는 정보를 저장하는 곳입니다. 여기서 reducer라는 개념이 새로 등장합니다. reducer는 간단하게, 1️⃣저장소(Store)에 있는 데이터를 수정하는 함수입니다. 2️⃣reducer가 return하는 값은 Store에 저장됩니다.

정리하자면, Store에 있는 data를 컨트롤하고 저장하는 중요한 함수라고 보면 됩니다.

reducer만이 데이터를 수정할 수 있기 때문에 추후에 데이터를 수정, 가공하기 위해서는 반드시 reducer를 거쳐야만 합니다.

import { createStore } from "redux"; // createStore 함수에게 전달할 reducer를 만듭니다. // reducer는 data를 수정(modify)할 함수입니다. const countModifier = () => { return "Hello" }; // 정보를 저장하는 store를 생성합니다. const countStore = createStore(countModifier);

여기서 Store란 객체가가 가지고 있는 함수를 살펴봅시다. 전부 다 알아야 하지만 가장 중요한 3개를 먼저 알아보겠습니다.

getState란 함수에는 reducer가 return한 값이 담겨 있으며

dispatch를 통해 reducer에게 action을 줄 수 있습니다.

subscribe는 store 안의 변화를 감지합니다. Store를 구독한다고 생각하면 됩니다. 데이터가 바뀔 때마다 업데이트할 때 자주 사용됩니다.

🚗 Reducer 두 번째 인자, action

Store가 가지고 있는 메소드 dispatch를 통해서 reducer로 액션을 보낼 수 있습니다. action은 reducer와 소통하는 방법입니다. 조금 규칙이 깐깐한데 반드시 객체를 보내야 하며, type이란 키를 반드시 줘야 합니다.

const countModifier = (count = 0, action) => { if (action.type === "plus") { return count + 1; } else if (action.type === "minus") { return count - 1; } else { return count; } }; const countStore = createStore(countModifier); countStore.dispatch({ type: "plus" }); countStore.dispatch({ type: "plus" }); countStore.dispatch({ type: "minus" }); console.log(countStore.getState()); // 3이 출력됩니다

🚗 getState, dispatch, subscribe로 간단한 카운터 제작

import { createStore } from "redux"; const Plus = document.querySelector(".plus"); const Minus = document.querySelector(".minus"); const output = document.querySelector(".output"); //reducer const countModifier = (count = 0, action) => { if (action.type === "plus") { return count + 1; } else if (action.type === "minus") { return count - 1; } else { return count; } }; //store const countStore = createStore(countModifier); //subscribe countStore.subscribe(() => { output.innerText = countStore.getState(); }); //dispatch Plus.addEventListener("click", () => { countStore.dispatch({ type: "plus" }); }); Minus.addEventListener("click", () => { countStore.dispatch({ type: "minus" }); });

🚨 swtich 문을 사용하던데...?

Redux 공식 문서에나 Redux를 사용하는 문서에서 종종 if문 보다 switch문을 더 자주 사용하곤 하는데 편한 대로 사용하면 된다. 필자는 if, else를 선호한다.

switch (action.type) { case "plus": return count + 1 case "minus": return count - 1 default: return count

from http://darrengwon.tistory.com/183 by ccl(A) rewrite - 2020-03-25 05:54:17

댓글

이 블로그의 인기 게시물

[Debugging] AngularJS2 - Can't bind to 'ngModel' since it isn't a...

[Debugging] AngularJS2 - Can't bind to 'ngModel' since it isn't a... - 좋아요 하이 .. !! Angular2 로 개발을 하다가 아래와 같은 에러를 만났다. 흠 .. 이게 뭘까 열심히 구글링을 해봤다. 간단한 내용이다. 모듈을 추가해주기만 하면 된다. app.module.ts를 열어보자. 여기에다가 FormsModule 과 ReactiveFormsModule을 추가해주면 문제가 해결된다 ! 다들 즐거운 코딩하자. from http://devkingdom.tistory.com/106 by ccl(A) rewrite - 2020-03-18 00:54:15

[aws] deploy Angular app with s3 | AWS S3로 angular 앱 배포하기

[aws] deploy Angular app with s3 | AWS S3로 angular 앱 배포하기 angular project를 빌드한다 ng build --prod 그러면 dist 폴더가 생긴다. dist 폴더 안에 있는 아이들을 사용한다. 아마존 s3 콘솔로 이동 https://s3.console.aws.amazon.com/s3/home?region=ap-northeast-2 새로운 Bucket 을 생성한다(Create bucket). 버킷 이름은 고유하게 짓는다. 버킷 생성후 properties tab > static website hosting을 클릭한다. index document는 index.html은 쓴다. properties > static website hosting Permission tab 에서 권한을 수정한다. overview tab 에서 필요한 파일 업로드 dist 폴더 안에 있는 파일들을 업로드 한다. bucket policy 설정 properties > static website hosting > endpoint 클릭하면 서버에 올라간 앱을 확인 할 수 있다 일단 angular 앱을 올리긴 했는데.. 이걸로는 아무것도 할 수 었다. django로 만든 서버를 올리고 database를 연결하고 그것을 지금 이 angular 앱과 연결해야한다. 아직 어떻게 해야 할지는 모르겠음 계속 삽질 중. 그래도 angular app 하나 올라갔는데 재밌네 from http://paigeblog.tistory.com/18 by ccl(A) rewrite - 2020-03-25 16:20:22

Angular2 시작하기

Angular2 시작하기 Angular2 시작하기 1. NodeJS 설치 - https://nodejs.org/ko/ NodeJS 공식 홈페이지 접속하여 Node를 다운 후 설치. 2. NPM 을 통한 Angular-Cli 설치 Window Command 를 통하여 npm install -g @angular/cli 명령어를 실행한다. 위와 같이 정상적으로 angular-cli 가 설치되었다면 Project 가 위치할 폴더를 생성. 참고 사이트 : https://cli.angular.io/ 3. Angular-cli 를 통한 Angular Project 생성. Window Command 를 통한 ng new [폴더명] 위와 같이 Angular 기본 프로젝트가 생성됨. 해당 프로젝트로 폴더로 이동하여 ng serve 명령어 실행 Node 를 통해 Angular 프로젝트 실행. http://localhost:4200 접속하게되면 위와같이 Angular 프로젝트 실행된다. 앞으로 Angular2 의 개념들을 포스팅하면서 Spring-Boot , Spring Project의 Angular-cli 를 이용하여 ng build 하여 포팅하는 글을 올리겠습니다. from http://overclassbysin.tistory.com/3 by ccl(A) rewrite - 2020-03-07 07:55:13