설치
npm install @reduxjs/toolkit react-redux
yarn add redux react-redux @reduxjs/toolkit
사용
스토어에 등록하는것은 이렇게!!!!!!
index.js
import { Provider } from "react-redux";
import store from "./store";
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
Provider 로 감싸주고 store.js 파일 생성해서 넘겨준다!
store.js
import { configureStore } from '@reduxjs/toolkit'
import cart from "./store/cartSlice";
export default configureStore({
reducer: {
cart: cart.reducer,
}
})
cartSlice.js
import { createSlice } from "@reduxjs/toolkit";
let cart = createSlice({
name: "cart",
initialState: [
{ id: 0, name: "White and Black", count: 2 },
{ id: 2, name: "Grey Yordan", count: 1 },
],
reducers: {
minusCount(state, action) {
let idx = state.findIndex((x) => x.id == action.payload);
if (state[idx].count > 1) {
state[idx].count--;
} else {
alert("최소 수량입니다.");
}
},
addCount(state, action) {
let idx = state.findIndex((x) => x.id == action.payload);
state[idx].count++;
},
},
});
export let { minusCount, addCount } = cart.actions;
export default cart;
스토어를 사용할때엔!!!
cart.js
import { useDispatch, useSelector } from "react-redux";
import { minusCount, addCount } from "../../store/cartSlice";
let state = useSelector((state) => state.cart);
let dispatch = useDispatch(); // store.js 로 요청 보내주는 함수
<button onClick={()=>{ dispatch(minusCount(item.id)); }}>-</button>