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;
// 원래부터 있던 코드
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();
(1) initialState === 초기상태값
// 초기 상태값
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
처럼 state
에 initialState
를 할당해줘야한다.(3) 카운터 모듈을 스토어에 연결하기
// 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;
// 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
});