1. 스토어 생성
index.js에
import { legacy_createStore as createStore } from 'redux';
import { Provider } from 'react-redux';
/** 스토어 생성 */
const store = createStore(rootReducer);
root.render(
<React.StrictMode>
<Provider store={store}> // 범위 설정
<RouterProvider router={router} />
</Provider>
</React.StrictMode>
);
createStore import 후 스토어 생성 그리고 범위 설정
2. 액션 리덕스 모듈(Reducer객체) 생성
reduxCount파일
const init = { count: 0, total: 0 };
export default function reduxCount(state = init, action) {
const tot = state.total
if (action.type === 'plus') {
return {
count: state.count + 1,
total: tot + (state.count + 1)
};
} else if (action.type === 'minus') {
return {
count: state.count - 1,
total: tot - 1
};
}
else if (action.type === 'reset') {
return { count: 0, total: 0 };
} else {
return state
}
}
state생성 후 default 리턴값을 생성 후 action.type값에 따라 다른 if문 생성
3. 여러개의 액션 리덕스 모듈을 합치기
store에서 사용한 rootReducer파일
import { combineReducers } from "redux";
import reduxCount from './reduxCount';
/**여러개의 reducer를 합치는 기능 */
const rootReducer = combineReducers({
reduxCount
// 추가할 여러개 reducer 추가 ...
}) ;
export default rootReducer;
reduxCount 라는 reduce 추가
4. 리액트 프로젝트에 리덕스 적용
1) 리덕스(sotre)와 리액트 연동을 위한 컨테이너 생성 : dispatch , useSelector
2) 컨테이너에서 컴포넌트 호출
import { useDispatch, useSelector } from "react-redux";
import CountItemRedux from './../components/CountItemRedux';
import CountTotal from "../components/CountTotal";
// 컴포넌트 이벤트 호출와 스토여 중개 역할
export default function CountContainer() {
//1. useSelector를 이용하여 리듀서의 total, count 값 가져오기
const { count, total } = useSelector(state => (
{
count: state.reduxCount.count,
total: state.reduxCount.total,
}))
//2. dispatch를 이용하여 액션 이벤트 함수 처리
const dispatch = useDispatch();
const onPlus = () => dispatch({ type: 'plus' });
const onMinus = () => dispatch({ type: 'minus' });
const onReset = () => dispatch({ type: 'reset' });
return (
<>
{/* total,count 값을 공유하는 컴포넌트 호출 */}
<CountItemRedux
count={count}
total={total}
onPlus={onPlus}
onMinus={onMinus}
onReset={onReset}
/>
<hr/>
<CountTotal total = {total}/>
</>
);
}
1. useSelector를 이용하여 리듀서의 total, count 값 가져오기
2. dispatch를 이용하여 액션 이벤트 함수 처리
3. 컴포넌트에 props로 전송

props값!
// import { useReducer, useState } from "react";
// import ageReducer from './../reducer/ageReducer';
export default function CountItemRedux(props) {
console.log(props);
return (
<>
<h1>Count : {props.count}</h1>
<p>
<button type="button" onClick={props.onPlus}>num ++ </button>
<button type="button" onClick={props.onMinus}>num -- </button>
<button type="button" onClick={props.onReset}>reset </button><br /><br />
</p>
<h3>total : {props.total}</h3>
<br />
<br />
<br />
<br />
</>
);
}
count 와 total값 그리거 dispatch를 활용한 함수 사용