설치
npm install @reduxjs/toolkit react-redux
import { configureStore } from "@reduxjs/toolkit";
export default configureStore({
reducer: {},
});
import store from "./store";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
</React.StrictMode>
);
import { configureStore, createSlice } from "@reduxjs/toolkit";
// useState 역할
// state 하나를 slice라고 부름
// 1. createSlice 만들기
createSlice({
name: "state이름",
initialState: "값",
});
let user = createSlice({
name: "user",
initialState: "kim",
});
// 2. 등록해야 사용 가능
export default configureStore({
reducer: {
user: user.reducer,
},
});
import React from "react";
import { Table } from "react-bootstrap";
import { useSelector } from "react-redux";
function Cart(props) {
let user = useSelector((state) => {
return state;
});
let user1 = useSelector((state) => {
return state.user;
});
// 원하는 것만 가져와서 사용 가능
console.log(user);
return (
...
);
}
export default Cart;
store.js
let cart = createSlice({
name: "stock",
initialState: [
{ id: 0, name: "White and Black", count: 2 },
{ id: 2, name: "Grey Yordan", count: 1 },
],
reducers: {
// 1. state 수정해주는 함수 만들기
addCount(state, action) {
// 2. state 는 기존 state, action 은 받아오는 state
let currentNumber = state.findIndex((data) => {
return data.id === action.payload;
});
state[currentNumber].count++;
},
addItem(state, action) {
state.push(action.payload);
},
},
});
// 3. 만든 함수 export
export let { addCount, addItem } = cart.actions;
// 4. 등록해야 사용 가능
export default configureStore({
reducer: {
user: user.reducer,
stock: stock.reducer,
cart: cart.reducer,
},
});
ProductDetail.js
// 5. 만들어둔 context import
import { useDispatch } from "react-redux";
const ProductDetail = () => {
// 6. dispatch 선언
let dispatch = useDispatch();
return (
...
<button
onClick={() => {
dispatch(
addItem({
id: findProduct.id,
name: findProduct.content,
count: stock[findProduct.id],
})
);
}}
>
주문하기
</button>
)
}