1 ๋ถ„ ์†Œ์š”

Redux(์ƒ)๐Ÿ“


npm install redux react-redux

redux๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ํ„ฐ๋ฏธ๋„์—์„œ ๋ช…๋ น์–ด๋ฅผ ํ†ตํ•ด ์„ค์น˜ํ•˜์ž.


๊ธฐ์ดˆ ๋ฌธ๋ฒ•๐Ÿšฉ

index.js

import { Provider } from "react-redux";
import { createStore } from "redux";

let store = createStore(reducer); //state๋งŒ๋“ค๊ธฐ

function reducer() {
  return [
    { id: 0, name: "์‹ ๋ฐœ", quan: 7 },
    { id: 1, name: "์ƒ์˜", quan: 18 },
  ];
}

ReactDOM.render(
    <Provider store={store} >
      <App />
    </Provider>
);

App.js

import React from "react";
import { connect } from "react-redux";

function Abcd(props) {
    return (
    	<div>
        	{props.์ž‘๋ช…} // ['a','b']
        </div>
    )
}

function ์ž‘๋ช…1(state) {
    return {
        ์ž‘๋ช…: state
    }
}

export default connect(state)(์ž‘๋ช…1);

โ€˜์ดˆ๊ธฐ์…‹ํŒ…โ€™

a,b๊ฐ€ ๋‹ด๊ธด store์„ ์–ด๋””์—์„œ๋‚˜ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.



index.js

let datastate = [
  { id: 0, name: "์‹ ๋ฐœ", quan: 2 },
  { id: 1, name: "์ƒ์˜", quan: 18 },
];

function reducer(state = datastate, action) {
  if (action.type === "inc") {
    let copy = [...state];
    copy[0].quan++;
    return copy;
  } else if (action.type === "dec") {
    let copy = [...state];
    copy[0].quan--;
    return copy;
  } else return state;
}

let store = createStore(reducer);

App.js

function Cart(props) {
    return(

    	{props.dispatch({ type: "inc" }}

    )

โ€˜Redux์˜ ๋ณ€์ˆ˜์˜ ๊ฐ’ ๋ณ€๊ฒฝโ€™

๋ณ€์ˆ˜์˜ ๊ฐ’์„ ๋ณ€๊ฒฝํ•˜๊ณ  ์‹ถ์„๋• ์ดˆ๊ธฐ์„ค์ •ํ–ˆ๋˜ ๊ณณ์—์„œ ๋ณ€๊ฒฝํ•  ์•ก์…˜์„ ๋งŒ๋“ค๊ณ  ์ž‘๋ช…ํ•œ๋‹ค.

๊ทธ๊ฒƒ์„ ํ•„์š”ํ•œ ๊ณณ๋งˆ๋‹ค ๋ถˆ๋Ÿฌ์˜ค๋Š” ์‹์œผ๋กœ ๋ณ€์ˆ˜์˜ ๊ฐ’์„ ๋ณ€๊ฒฝํ•˜๋Š”๋ฐ ์ด ๋ฐฉ๋ฒ•์€ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋งŽ์„๋•Œ ์—๋Ÿฌ๋ฅผ ์žก๊ธฐ์— ์•„์ฃผ ํŽธ๋ฆฌํ•˜๋‹ค.



index.js

function reducer(state = datastate, action) {}

function reducer2(state = opneclose, action) {}

let store = createStore(combineReducers({ reducer, reducer2 }));

app.js

function state(state) {
  return {
    a: state.reducer,
    b: state.reducer2,
  };
}

export default connect(state)(Cart);

โ€˜2๊ฐœ์ด์ƒ์˜ Reducer๋งŒ๋“ค๊ธฐโ€™

๋ณ€์ˆ˜๋ฅผ ํ•œ๊ฐœ๋” ๋งŒ๋“ค๊ณ  ์‹ถ๋‹ค๋ฉด combineReducers๋ฅผ ํ†ตํ•ด ๋” ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.

์—…๋ฐ์ดํŠธ: