[React] 6. Redux 3 (more reducer)

glow_soon·2022년 2월 11일
0

React

목록 보기
25/52
post-thumbnail

다른 정보도 state로 만들어서 reducer로 쓰고싶다면?

우선 나의 귀여운 alert창을 하나 만들었다. 부트스트랩 복붙함ㅎㅎ

state에 열기/닫기 상태를 저장하고 싶다

추가로 state를 저장하고 싶으면 그냥 reducer를 하나 더 만들면 된다

import { combineReducers, createStore } from "redux";

let 초기값 = [
  { id: 0, name: "fucking shoes", quan: 2 },
  { id: 1, name: "pretty shoes", quan: 10 },
  { id: 2, name: "dirty shoes", quan: 1 },
  { id: 3, name: "normal shoes", quan: 3 },
];

let alertClose = true;

function reducer2(state = alertClose, 액션) {
  if (액션.type === "닫기") {
    state = false;
    return state;
  } else {
    return state;
  }
}

function reducer(state = 초기값, 액션) {
  if (액션.type === "수량증가") {
    let copy = [...state];
    copy[0].quan++;
    return copy;
  } else if (액션.type === "수량감소") {
    let copy = [...state];
    copy[0].quan--;
    if (copy[0].quan < 0) {
      copy[0].quan = 0;
    }
    return copy;
  } else {
    return state;
  }
}

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

combineReducers()안에 모든 리듀서를 object형식으로 담아야 한다, import도 잘하기

//Cart.js
function state를props화(state) {
  //console.log(state);
  return {
    상품: state,
  };
}

reducer를 여러개 만들었으면 잘 골라서 써야한다, 이렇게 그냥 쓰면 error발생

//Cart.js
function state를props화(state) {
  //console.log(state);
  return {
    상품: state.reducer, // 리듀서1에 담긴 데이터
    alert: state.reducer2, //리듀서2에 담긴 데이터
  };
}

이렇게 뽑아서 써야한다

{props.alert ? (
        <Alert variant="primary">
          <p>지금 구매하시면 신규할인 20%</p>
          <button
            onClick={() => {
              props.dispatch({ type: "닫기" });
            }}
          >
            Close
          </button>
        </Alert>
      ) : null}

dispatch()와 삼항연산자를 잘 써주면 끝!!!
잘 작동한다ㅎㅎ

But, 이런식으로 redux쓰면 안됨
UI 하나 만드는데 redux에 굳이 저장할 필요는 없다. state 데이터가 다른 컴포넌트에서 쓸일이 없다면 그냥 해당 컴포넌트안에서 useState()로 간단히 구현하자
많은 컴포넌트들이 공유하는 값은 redux store안에 보관하기!!

출처 : https://codingapple.com/ (코딩애플님 리액트 강의)

profile
나는야 코린이

0개의 댓글