vue처럼 배경 component(부모) 에서 자식 component로 data를
porps해줘야하는데 매번 props를 하기 힘들때 사용하는 게 Redux라는 개념이다.
Redux가 뭘해주는데?
그놈의 상태관리.....
여러 컴포넌트들이 하나의 값을 공동으로 수정할 때 Redux로 하나의 js에서 그 값을 관리하도록하는 것.
component 들이 수정을 요청하면 store.js에서 값이 조정된다.
=> state 관리가 용이하다 = 값을 한 곳에서 관리가 가능.
마치 전역변수같은 느낌이 든다.
Redux 구현방법
index.js
_ state 관련 기능을 정의하고 이곳에서 상태를 계속 변경시킨다.
// index.js 여기에 state 수정방법을 정의해놓음.
import {Provider} from 'react-redux';
import {createStore} from 'redux';
const 체중 = 100;
function reducer(state = 체중, action){
if(action.type === '증가'){ // 어떤 component가 증가요청을 할때 +1
state++;
return state
} else if(action.type === '감소'){ // 어떤 component가 감소요청을 할때 +1
state--;
return state
} else {
return state
}
}
App.js
_ dispatch를 통해 index.js에 정의한 기능별 state 값 변경을 요청한다.
// index.js에 정의해놓은 state 수정요청 기능을 컴포넌트에서 요청하는 법
// redux에서 제공하는 redux 메서드를 사용해 state 변경 요청을 날림.
import './App.css';
import {useSelector} from 'react-redux'
function App() {
const 꺼내온거 = useSelector((state) => state);
return (
<div className = "App">
<p>님의 처참한 몸무게 : {꺼내온거}</p>
<button onClick={()=>{dispatch({type : '증가'}) }}>더하기</button>
</div>
);
}
export defalut App;
참고 동영상 | https://www.youtube.com/watch?v=QZcYz2NrDIs