[REACT] 14_장바구니(카트) 기능 구현 2

2021. 12. 27. 13:17React/React 쇼핑 앱

반응형

장바구니(카트) 기능 구현 2

수량 증가 / 수량 감소 버튼에 대한 기능구현

 

index.js

더보기
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';
import { combineReducers, createStore } from 'redux';
import { Provider } from 'react-redux';

let reducer1State = [];


export const reducer1 = (state = reducer1State, action) => {
  if (action.type === 'addObj') {
    let foundObjIdx = state.findIndex((obj) => {
      return obj.id === action.data.id
    });
    console.log('찾아진 객체 인덱스 : ' + foundObjIdx);
    if (foundObjIdx >= 0) {
      let _state = [...state];
      _state[foundObjIdx].qty++;
      return _state;
    } else {
      let _state = [...state];
      _state.push(action.data);
      console.log(_state);
      return _state;
    }
  } else if (action.type === 'plusQTY') {
    let _state = [...state];
    console.log(_state[action.data]);
    console.log(action.data);
    _state[action.data].qty++;
    return _state;
  } else if (action.type === 'minusQTY') {
    let _state = [...state];
    _state[action.data].qty--;
    return _state;
  } else {
    return state;
  }
}

let store = createStore(combineReducers({
  reducer1
}));


ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <Provider store={store}>
        <App />  
      </Provider>
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

 

Cart.js

더보기
import { Table } from "react-bootstrap";
import { useDispatch, useSelector } from "react-redux";

function Cart(props) {
  let state = useSelector((state) => state);
  let dispatch = useDispatch();
  return (
    <>
      <Table responsive>
        <thead>
          <tr>
            <th>#</th>
            <th>상품명</th>
            <th>가격</th>
            <th>수량</th>
            <th>변경</th>
          </tr>
        </thead>
        <tbody>
          {
            state.reducer1.map((obj, i) => {
              return (
                <tr key={i}>
                  <td>{obj.id}</td>
                  <td>{obj.name}</td>
                  <td>{obj.price}</td>
                  <td>{obj.qty}</td>
                  <td>
                    <a class="btn btn-secondary" role="button" onClick={() => {
                      dispatch({
                        type: 'plusQTY',
                        data: obj.id
                      });
                    }}>+</a>
                    &nbsp;
                    <a class="btn btn-secondary" role="button" onClick={() => {
                      dispatch({
                        type: 'minusQTY',
                        data: obj.id
                      });
                    }}>-</a>
                  </td>
                </tr>
              )
            })
          }
          {/* <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
            <td>4</td>
          </tr> */}
        </tbody>
      </Table>
    </>
  )
}

export default Cart;

반응형