TIL29-01 Redux 설정

김태혁·2023년 2월 11일
0

TIL

목록 보기
93/205

1. Redux 설정

  • 리덕스 패키지 설치 yarn add redux react-redux
  • 리덕스 파일
  • redux파일 생성 : 리덕스 관련 코드를 모두 몰아 넣음
  • redux/config : 파일 생성 리덕스 설정 관련 파일 전부
  • configStore.js : 중앙 state 관리소 -> 설정 코드(.js)
  • redux/modules파일 생성 : state의 그룹! ex) TodoList. todos.js

configstore.js

import { createStore } from "redux";
import { combineReducers } from "redux";

/*
1. createStore()
리덕스의 가장 핵심이 되는 스토어를 만드는 메소드(함수)다.
리덕스는 단일 스토어로 모든 상태 트리를 관리한다. 
리덕스를 사용할 시 creatorStore를 호출할 일은 한 번밖에 없다.
*/

/*
2. combineReducers()
리덕스는 action —> dispatch —> reducer 순으로 동작한다. 
이때 애플리케이션이 복잡해지게 되면 reducer 부분을 여러 개로 나눠야 하는 경우가 발생한다.
combineReducers은 여러 개의 독립적인 reducer의 반환 값을 하나의 상태 객체로 만들어준다.
*/

const rootReducer = combineReducers({}); 
const store = createStore(rootReducer); 

export default store; 

index.js

  • 디렉토리 가장 최상단에 있는 `index.js에 아래 내용을 입력한다.
// 원래부터 있던 코드
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import reportWebVitals from "./reportWebVitals";

// 우리가 추가할 코드
import store from "./redux/config/configStore";
import { Provider } from "react-redux";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(

	//App을 Provider로 감싸주고, configStore에서 export default 한 store를 넣어줍니다.
  <Provider store={store}> 
    <App />
  </Provider>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

2. 모듈 만들기

2.1 모듈의 구성요소

(1) initialState === 초기상태값

  • 아래 코드에서만든 State의 초기값은 { } (객체) 이고, 그 안에 number 라는 변수에 초기값 0을 할당해준 것이다. 초기값은 꼭 객체가 아니어도 된다. 배열이 되어도 되고, 그냥 원시데이터가 돼도 된다. 그리고 객체에도 여러개의 변수를 넣어줄 수 있.
// 초기 상태값
const initialState = {
  number: 0,
};

// 초기값이 0
const initialState = 0;

// 초기값이 0이 있는 배열 
const initialState = [0];

// 초기값이 number = 0, name = '석구'인 객체
const initialState = {
	number: 0,
	name: '석구'
};

(2) Reducer === 변화를 일으키는 함수

  • 우리가 useState()를 사용할 때, number라는 값을 바꾸고 싶으면 setNumber를 사용했다. 리덕스에서는 리듀서가 이 역할을 한다. 아래는 예시 코드.
// src/redux/modules/counter.js


// counter 리듀서
const counter = (state = initialState, action) => {
  switch (action.type) {
    default:
      return state;
  }
};

export default counter; // 여기
  • 리듀서의 인자에 보면 (state = intialState, action) 이라고 되어 있다. 우리는 리듀서 인자 첫번째 자리에서는 state를, 두번째 자리에서는 action 이라는 것을 꺼내서 사용할 수 있다. state = intialState 처럼 stateinitialState를 할당해줘야한다.

(3) 카운터 모듈을 스토어에 연결하기

  • 만든 모듈을 스토어에 연결 시켜야 한다. 아직까진 모듈과 스토어가 각각 따로 분리되어 있는 상태이기 때문에 우리가 만든 State를 스토어에서 꺼낼 수 없다.
  • configStore.js로 이동해서 아래 코드를 추가한다.
// src/redux/modules/config/configStore.js


// 원래 있던 코드
import { createStore } from "redux";
import { combineReducers } from "redux";

// 새롭게 추가한 부분
import counter from "../modules/counter";

const rootReducer = combineReducers({
  counter: counter, // <-- 새롭게 추가한 부분
});
const store = createStore(rootReducer);

export default store;

3. 스토어와 모듈 연결 확인하기

useSelector = 스토어 조회

  • 컴포넌트에서 리덕스 스토어를 조회하고자 할때는 useSelector라는 ‘react-redux’의 훅을 사용한다.
// 1. store에서 꺼낸 값을 할당 할 변수를 선언한다.
const number = 

// 2. useSelector()를 변수에 할당해준다.
const number = useSelector() 

// 3. useSelector의 인자에 화살표 함수를 넣어준다.
const number = useSelector( ()=>{} )

// 4. 화살표 함수의 인자에서 값을 꺼내 return 한다.
// 우리가 useSelector를 처음 사용해보는 것이니, state가 어떤 것인지 콘솔로 확인한다.
const number = useSelector((state) => {
	console.log(state)
	return state
});
  • 브라우저를 켜고, 콘솔을 보면 객체가 보이고, 그 안에 counter 라는 값이 있는 것을 볼 수 있다. 우리가 만든 counter 라는 모듈의 state가 보이는 것을 알 수 있다. 이렇게 화살표 함수에서 꺼낸 state라는 인자는 현재 프로젝트에 존재하는 모든 리덕스 모듈의 state 인 것이다.
profile
도전을 즐기는 자

0개의 댓글