[React.js] Redux (4)


๐Ÿš€ย 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;