반응형
Redux란?
predictable state container for JavaScript apps. 상태 관리 라이브러리로 state을 관리해주는 기능을 하고 있다.
여기서 State이란 컴포넌트 안에서 데이터를 교환하거나 전달할 때 사용한다.
Redux을 쓰는 이유
- 상위 컴포넌트에 comments 들의 정보를 다 보관하고 있다. 하지만 comments 을 관리하는게 이 한 컴포넌트만 있는 것이 아니라이 컴포넌트의 자식 컴포넌트에서도 comments 를 관리하고 그 자식 컴포넌트에서도 comments를 관리하고 있는게 문제이다.
- 즉 comments의 state는 최상위 컴포넌트에서 관리되고 있음최하위 컴포넌트에서 Action이 일어났을 때 이 행위를 최상위 컴포넌트에 알려줘야하는데 이때 Redux가 없을 때는 컴포넌트들을 하나하나 타고 올라가야하며 또 최상위 컴포넌트의 정보를 하나하나 타고 내려줘야하는 복잡성이 문제가 된다.
- 이럴 때 Redux는 Redux Store에 컴포넌트의 변화를 저장시켜주고 받아올 때도 Redux Store에서 받아오면 되면서 State 관리를 할 수 있게 되는 것이다.
Redux 다운로드
아래 사이트가 다운로드 및 Redux에 관한 내용이 적혀있는 사이트이다.
https://www.npmjs.com/package/redux
redux
Predictable state container for JavaScript apps
www.npmjs.com
npm install --save redux
위의 코드를 프롬프트에 입력하여 npm을 통한 다운로드가 가능하다.
import { createStore } from 'redux'
그리고 위의 코드를 Redux을 적용시킬 코드에 붙여놓기 한다.
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/4.4.5/react-redux.js"></script>
npm을 못쓴다면 위의 cdn을 붙여주면 된다.
Redux을 쓰지 않을때
아래와 같은 코드는 3개의 컴포넌트가 연결되어 있어 한 컴포넌트를 수정하면 다른 나머지 컴포넌트까지 수정해야하는 번거로움이 존재하는 매우 단순한 코드이다.
배경화면이 red로 바뀌는 버튼을 누르면 다른 곳에 적용되어 있는 red 버튼의 코드를 가진 컴포넌트들도 함께 바뀌는 그러한 코드이다.
<html>
<body>
<style>
.container{
border:5px solid black;
padding:10px;
}
</style>
<div id="red"></div>
<div id="green"></div>
<div id="blue"></div>
<script>
function red(){
document.querySelector('#red').innerHTML = `
<div class="container" id="component_red">
<h1>red</h1>
<input type="button" value="fire" onclick="
document.querySelector('#component_red').style.backgroundColor = 'red';
document.querySelector('#component_green').style.backgroundColor = 'red';
document.querySelector('#component_blue').style.backgroundColor = 'green';
">
</div>
`;
}
red();
function green(){
document.querySelector('#green').innerHTML = `
<div class="container" id="component_green">
<h1>green</h1>
<input type="button" value="fire" onclick="
document.querySelector('#component_red').style.backgroundColor = 'green';
document.querySelector('#component_green').style.backgroundColor = 'green';
document.querySelector('#component_blue').style.backgroundColor = 'green';
">
</div>
`;
}
green();
function blue(){
document.querySelector('#blue').innerHTML = `
<div class="container" id="component_blue">
<h1>blue</h1>
<input type="button" value="fire" onclick="
document.querySelector('#component_red').style.backgroundColor = 'blue';
document.querySelector('#component_green').style.backgroundColor = 'blue';
document.querySelector('#component_blue').style.backgroundColor = 'blue';
">
</div>
`;
}
blue();
</script>
</body>
</html>
반응형
'프로그래밍 개발 > Redux' 카테고리의 다른 글
Redux - Redux로 간단한 웹사이트 구현하기 (0) | 2021.01.23 |
---|---|
Redux - Redux 구현하기 (0) | 2021.01.23 |
댓글