액션함수생성
export const INCREASE = 'INCREASE';
export const DECREASE = 'DECREASE';
export const increase = () => {
return {
type: INCREASE,
};
};
export const decrease = () => {
return {
type: DECREASE,
};
};
리듀서함수생성
//initialState는 1
import { initialState } from './initialState.js';
import { INCREASE, DECREASE } from '../Actions';
export const counterReducer = (state = initialState, action) => {
switch (action.type) {
case INCREASE:
return state + 1;
case DECREASE:
return state - 1;
default:
return state;
}
};
스토어 생성
import { legacy_createStore as createStore } from 'redux';
import { counterReducer } from '../Reducers';
export const store = createStore(counterReducer);
최상위 인덱스
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux';
import { store } from './Store';
const rootElement = document.getElementById('root');
const root = createRoot(rootElement);
root.render(
<Provider store={store}>
<App />
</Provider>
);
APP.js
import React from 'react';
import './style.css';
import { useSelector, useDispatch } from 'react-redux';
import { increase, decrease } from './Actions';
export default function App() {
const counter = useSelector((state) => state);
const dispatch = useDispatch();
const plusNum = () => {
dispatch(increase());
};
const minusNum = () => {
dispatch(decrease());
};
return (
<div className="container">
<h1>{`Count: ${counter}`}</h1>
<div>
<button className="plusBtn" onClick={plusNum}>
+
</button>
<button className="minusBtn" onClick={minusNum}>
-
</button>
</div>
</div>
);
}
