๐ย Redux ์์
์์
1. ์ก์
ํ์
์ ์ํ๊ธฐ
(...)
/* 1. ์ก์
ํ์
์ ์ํ๊ธฐ (const ๋ณ์ = "ํ์ผ๋ช
/์ก์
๋ช
") */
const RED = "color/RED"
const GREEN = "color/GREEN"
const BLUE = "color/BLUE"
const PINK = "color/PINK"
2. ์ก์
์์ฑ ํจ์ ๋ง๋ค๊ธฐ ๋ฐ ์ก์
๋ด๋ณด๋ด๊ธฐ
(...)
/* 2. ์ก์
์์ฑ ํจ์ ๋ง๋ค๊ธฐ ๋ฐ ์ก์
๋ด๋ณด๋ด๊ธฐ */
export const red = () =>({type:"RED"})
export const green = () =>({type:"GREEN"})
export const blue = () =>({type:"BLUE"})
export const pink = () =>({type:"PINK"})
3. ์ด๊ธฐ ์ํ ๋ฐ ๋ฆฌ๋์ ํจ์ ๋ง๋ค๊ธฐ
//3. ์ด๊ธฐ๊ฐ ๋ฐ ๋ฆฌ๋์ ์์ฑ
const initialState = {
color: "green",
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case CHANGE_COLOR:
return {
color: action.color,
//action.๋งค๊ฐ๋ณ์
};
default:
return state;
}
};
export default reducer;
4. ๋ฃจํธ ๋ฆฌ๋์ ๋ง๋ค๊ธฐ
//store/index.js
/* 4. ๋ฃจํธ ๋ฆฌ๋์ ๋ง๋ค๊ธฐ */
export default combineReducers({
color,
});
5. ์คํ ์ด ๋ง๋ค๊ธฐ
//src/index.js
/* 5. ์คํ ์ด ๋ง๋ค๊ธฐ */
const store = createStore(rootReducer, composeWithDevTools());
6. Provider ์ปดํฌ๋ํธ๋ฅผ ์ฌ์ฉํ์ฌ ํ๋ก์ ํธ์ ๋ฆฌ๋์ค ์ ์ฉํ๊ธฐ
//src/index.js
/* 6. Provider ์ปดํฌ๋ํธ๋ฅผ ์ฌ์ฉํ์ฌ ํ๋ก์ ํธ์ ๋ฆฌ๋์ค ์ ์ฉํ๊ธฐ */
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById("root")
);
reportWebVitals();
7. ์ปจํ
์ด๋ ์ปดํฌ๋ํธ ๋ง๋ค๊ธฐ
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { blue, green, pink, red } from "../store/modules/color";
/* 7. ์ปจํ
์ด๋ ์ปดํฌ๋ํธ ๋ง๋ค๊ธฐ */
const Color = () => {
// const state๋ด์์ด๋ฆ = useSelector( state => state.๋ฆฌ๋์ํ์ผ๋ช
.state๋ช
)
const color = useSelector((state) => state.color.color);
// ๋๋ฒ์งธ๋ ๋ฆฌ๋์ํ์ผ๋ช
, ์ธ๋ฒ์งธ๋ initalstate
const dispatch = useDispatch();
return (
<div>
<h1 style=>์ปฌ๋ฌ : {color}</h1>
<p>
<button onClick={() => dispatch(red())}>red</button>
<button onClick={() => dispatch(green())}>green</button>
<button onClick={() => dispatch(blue())}>blue</button>
<button onClick={() => dispatch(pink())}>pink</button>
</p>
</div>
);
};
export default Color;