리덕스를 사용하려면 설치부터 해야한다.

https://ko.redux.js.org/introduction/installation/

 

설치 | Redux

소개 > 설치: Redux와 관련 패키지 설치 방법

ko.redux.js.org

redux 공식 홈페이지에 설치 방법과 사용 방법이 자세하게 나와있으니 참고하면 된다.

 

이전 포스트에서 redux 없이 만든 웹 애플리케이션을 그대로 사용할 것이다.

color_change_redux.html

 

html에서 간단하게 redux를 사용할 때는 cdn을 사용하면 된다.

https://cdnjs.com/libraries/redux

 

redux - Libraries - cdnjs - The #1 free and open source CDN built to make life easier for developers

Predictable state container for JavaScript apps - Simple. Fast. Reliable. Content delivery at its finest. cdnjs is a free and open-source CDN service trusted by over 12.5% of all websites, serving over 200 billion requests each month, powered by Cloudflare

cdnjs.com

color_change_redux.html

 

리덕스를 사용한다는 것은 store를 만들어서 그 store의 상태를 바꾸는 것을 의미한다.

그러니 가장 먼저 store를 만들고 reducer 함수를 만들어서 store에 주입해주어야 한다.

color_change_redux.html

Redux.createStore()로 store를 생성할 수 있다. store를 생성한 다음에 reducer 함수를 만들어 store와 연결시켜줘야 한다.

reducer() 함수는 state와 action을 인수로 전달받는다. 우선 store의 state를 초기화시켜야하기 때문에 reducer() 함수 내부에 "if (state === undefined) {}" 구문을 넣어 state가 아무것도 없을 때, 즉 store를 처음 만들었을 때 초기 state 값을 반환하도록 한다.

 

이렇게 만들어진 store의 state를 확인하려면 store에 getState() 메소드를 사용하면된다.

color_change_redux.html
콘솔 화면

getState() 메소드의 반환값을 console에 출력되게 하면 현재 store의 state 값을 확인할 수 있다.

 

이 state 값은 "${}"로 변수처럼 사용할 수 있다.

color_change_redux.html
브라우저 화면

브라우저 화면에서 container의 background-color가 state.color인 yellow로 적용된 것을 볼 수 있다.


부스트코스의 강의 내용을 정리한 포스트입니다.

https://www.boostcourse.org/web231/lecture/1387449

 

웹 프론트엔드 시작하기 (리액트&리덕스)

부스트코스 무료 강의

www.boostcourse.org

BELATED ARTICLES

more