
Detail(์ํ์ ๋ณด ํ์ด์ง)์์ ์ฃผ๋ฌธํ๊ธฐ ๋ฒํผ ํด๋ฆญ ์ Cart(์ฅ๋ฐ๊ตฌ๋ ํ์ด์ง)์ ํด๋น ์ํ์ด ์ถ๊ฐ๋๋ ๊ธฐ๋ฅ
Redux๋ props ์์ด state๋ฅผ ๊ณต์ ํ ์ ์๊ฒ ๋์์ฃผ๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ด๋ค//store.jsx
import { configureStore, createSlice } from "@reduxjs/toolkit";
const cart = createSlice({
name: "cart",
initialState: [ // ๊ธฐ๋ณธ๊ฐ์ผ๋ก ๋ณด์ฌ์ง ๋ฐ์ดํฐ๋ค
{ id: 0, name: "White and Black", count: 2 },
{ id: 2, name: "Grey Yordan", count: 1 },
],
reducers: {
addItem(state, action) {
const sameNumber = state.filter(num => {
return num.id === action.payload.id;
});
if (sameNumber.length) {
alert("๋์ผํ ์ํ์ด ์์ต๋๋ค");
} else {
state.push(action.payload);
}
},
},
});
export const { addItem } = cart.actions; // addItem ๋ด๋ณด๋ด๊ธฐ
export default configureStore({
reducer: {
cart: cart.reducer,
},
});
๊ธฐ์กด state์ action.payload.id ๊ฐ์ ๋น๊ตํด์ ๊ฐ์ ๊ฐ์ ๋ฐํํ๋ค. ๋ฐํํ ๊ฐ์ ๊ธธ์ด์ ๋๊ฐ์ ์ํ์ด ์๋ค๋ฉด ๋์ผํ ์ํ์ด ์๋ค๊ณ ์๋ฆผ์ฐฝ์ ๋์ฐ๊ณ ๊ทธ๊ฒ ์๋๋ผ๋ฉด ์ํ ๋ฐ์ดํฐ๋ฅผ ์ถ๊ฐํ๋ ๊ธฐ๋ฅ์ด๋ค
// Detail.jsx
const Detail = ({ shoes }) => {
const { id } = useParams();
const products = shoes.find((product) => product.id === parseInt(id));
const dispatch = useDispatch();
return(
<div>
<button
className="btn btn-danger"
onClick={() => {
dispatch(
addItem({
id: products.id,
name: products.title,
count: 1,
})
);
}}
>
์ฃผ๋ฌธํ๊ธฐ
</button>
</div>
);
};
export default Detail;

<button
className="btn btn-danger"
onClick={() => {
dispatch(
addItem({ //๋ฐ๋ก ์คํ๋์ง ์์. store.jsx ํ์ผ์ ์์ฒญ
`id: ${products.id},
name: ${products.title},
count: 1,`
})
);
}}
>
์ฃผ๋ฌธํ๊ธฐ
</button>;
addItem ํจ์๋ก ๋ณด๋ธ ๋ฐ์ดํฐ๊ฐ Templeate Literal ๋ฐฉ๋ฒ์ธ ๋ฌธ์์ด์ด์๋ค. ๊ทธ๋ ๊ธฐ ๋๋ฌธ์ ๊ฐ์ฒด๋ก ๋ฐ์ดํฐ๋ฅผ ๋ณด๋ด์ผ์ง const sameNumber = state.filter(num => { return num.id === action.payload.id; }); ์ด ์ฝ๋์ฒ๋ผ filter๋ฉ์๋๋ฅผ ์ฌ์ฉํด์ ๋น๊ต๊ฐ ๊ฐ๋ฅํด์ง๋ค. ์ฆ ๋๋ aciton.payload.id๋ฅผ state๋ ๋น๊ตํ ๊ฒ ์๋๋ผ ๋ฌธ์์ด id๋ฅผ ๋น๊ตํ๊ธฐ ๋๋ฌธ์ ์ฅ๋ฐ๊ตฌ๋ ํ์ด์ง์ ํด๋น ์ํ๋ด์ญ์ด ๋ ๋๋ง ๋์ง ์์๋ ๊ฒ์ด๋ค