본문 바로가기
프런트엔드/React

React, Redux

by greenyellow-s 2024. 11. 4.
728x90
Redux

 

 

- 리덕스를 사용하면 컴포넌트들의 상태 관련 로직들을 다른 파일들로 분리시켜서 더욱 효율적으로 관리 할 수 있으며 글로벌 상태 관리도 손쉽게 할 수 있다.

- 상태값을 컴포넌트에 종속시키지 않고, 상태 관리를 컴포넌트의 바깥에서 관리 할 수 있게 된다.

- Redux React는 독립적으로 사용될 수 있는 별개의 다른 라이브러리이다.

- Redux는 자바스크립트 어플리케이션에서 흔히 쓰이는 상태관리 라이브러리이다.

- Redux Angular, Vue, Ember, jQuery 또는 Vanilla JavaScript와 같은 다른 라이브러리, 프레임워크에서도 사용할 수 있다

 

[설치]

1.

yarn add react-redux ( npm install react-redux / npm i react-redux )

yarn add redux  리덕스가 제대로 설치가 안 되면 또 한 번 한다.

 

2.

yarn add redux-devtools-extension ( npm i redux-devtools-extension )

 

 

웹스토어 redux-devtools-extension

 

 


index.js

 

import {Provider} from 'react-redux';
import rootReducer from './store';

//import {createStore} from 'redux'; - deprecated, 실행은 된다.
import {legacy_createStore as createStore} from 'redux'; //console을 보려면 이걸로

import {composeWithDevTools} from 'redux-devtools-extension';

//const store = createStore(rootReducer);
const store = createStore(rootReducer, composeWithDevTools());

const root = ReactDOM.createRoot(document.getElementById('root'));

{/* 저장소 */}
<Provider store={store}> 
	<App />
	{/* <App/>의 후손까지 모두 store를 사용해도 된다. */}
</Provider>

 

 

color.jsx

 

//1. 액션생성
// 모듈 이름을 앞에 붙여주어서 액션명 중복 방지
const RED = 'color/RED'; // 모듈이름/
const GREEN = 'color/GREEN'; 
const BLUE = 'color/BLUE'; 
const MAGENTA = 'color/MAGENTA'; 

//2. 액션 보내기
export const red = () => ({ type : RED })
export const green = () => ({ type : GREEN })
export const blue = () => ({ type : BLUE })
export const magenta = () => ({ type : MAGENTA })

//3. 초기값
const inintialState = {color : 'hotpink'}

//4. 리듀서 만들기 - state, action 파라메터를 참조하여, 새로운 상태 객체를 만든다.
//state - 현재상태, action - 액션 객체(위에서 잡아놓은거)
//반드시 state에는 초기값을 주어야 한다.
const reducer = (state=inintialState, action) => {
    switch(action.type){
        case RED : return {color : 'red'}
        case GREEN : return {color : 'green'}
        case BLUE : return {color : 'blue'}
        case MAGENTA : return {color : 'maenta'}
        default : return state
    }
}
export default reducer//컴포넌트가 아니라 순수 JS파일이다.

 

 

index.jsx

 

import { combineReducers } from "redux";
import color from './modules/color';

export default combineReducers({
    //이름(아무렇게나 해도 되는데 보통 리듀서 이름을 따라간다.) : 값(리듀서의 이름)
    color : color
    //똑같은게 두 개이면 하나만 써도 된다. color
})

 

 

Color.jsx
import {red, green, blue, magenta} from '../store/modules/color';

const color = useSelector(state => state.color.color);
//             index.jsx(이름) -> 리듀서의 이름 | color.jsx(리듀서) -> 액션으로 내보내버린 color값

//color.jsx에서 선언한 액선을 가져온다.
const dispatch = useDispatch();

return ..
	<button onClick={() => dispatch(red())}>RED</button>
    ..
)};

 

 

상태변수를 바꾸려면 setColor로 종속되게 했는데

그러면 나밖에 못가진다.

 

그래서 내가 가지고 있지 않고 store에 따로 가지고 있어서 (color.jsx)가 관리한다.

 

그래서 이 모듈 안에 있어요 라고 선언하는게

useSelector(state => state.color.color)이다.

 

-> index.jsxcombineReducers(부모) 에 자식 (color)리듀서를 찾는다.

-> color리듀서의 값은 color.jsx 가 된다.

-> color리듀서 값의 color라는 상태변수 값을 가져오겠다는 얘기

 

dispatch로 요청하면 그걸 받아서 처리

reducer리듀서 에 type이 같은거를 호출해서 export한다.

728x90