[REACT] 14_장바구니(카트) 기능 구현 2
2021. 12. 27. 13:17ㆍReact/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>
<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;
반응형
'React > React 쇼핑 앱' 카테고리의 다른 글
[REACT] 16_lazy 로딩 : 상세 페이지 (0) | 2021.12.27 |
---|---|
[REACT] 15_CSS = > SCSS 변환 (0) | 2021.12.27 |
[REACT] 13_장바구니(카트) 기능 구현 이슈 수정 (0) | 2021.12.27 |
[REACT] 12_장바구니(카트) 작성 및 브라우저 라우팅 (0) | 2021.12.27 |
[REACT] 11_상세페이지 작성 2 : 리덕스 상태관리 (0) | 2021.12.27 |