store
import { Provider } from "react-redux";
import { createStore } from "redux";
import rootReducer from "./store/reducers"
const store = createStore(rootReducer);
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<Routes />
<GlobalStyle />
</Provider>
</React.StrictMode>,
document.getElementById("root")
);
Provider
로 감싸진 하위 컴포넌트들은 props
를 내려주지 않아도 store
의 state
를 공유한다.
import { useSelector, useDispatch } from "react-redux";
import { deleteCart } from "../store/actions"
export default function CartItem({
isChecked,
product_name,
product_img,
price,
idx,
}) {
const dispatch = useDispatch();
const cartItems = useSelector((store) => store.cartReducer);
const filterItem = () => {
const items = cartItems.filter((_, i) => i !== idx);
dispatch(deleteCart(items));
};
return (
<Item>
<CheckColumn>
<CheckBox isChecked={isChecked} />
</CheckColumn>
<ImgColumn>
<Img src={product_img} />
</ImgColumn>
<ProductInfo>
<p>{product_name}</p>
<p>{price.toLocaleString()} 원</p>
</ProductInfo>
<td>1</td>
<td>{price.toLocaleString()} 원</td>
<td>
<DeleteCircle onClick={ filterItem }>
<DeleteIcon />
</DeleteCircle>
</td>
</Item>
);
}
useSelector
로 store
에서 state
를 가져온다.dispath
로 액션객체를 전달해준다.export const addCart = (item) => {
return {
type: "ADD_CART",
payload: item // dispath로 전달된 state
}
}
export const deleteCart = (items) => {
return {
type: "DELETE_CART",
payload: items
}
}
액션 파일에선 액션 객체 생성 함수를 작성한다.
액션 객체 생성 함수는,
type
과 state
를 객체로 담아서 리턴한다.type
은 필수값이며 상수이기 때문에 대문자로 작성한다.state
는 payload를 키값으로 하는것이 컨벤션이다.const initialstate = [];
const cartReducer = (state = initialstate, action) => {
// action.type에 따라 실행하는 switch문
switch (action.type) {
case "ADD_CART" :
// redux는 불변성을 지켜야 하기 때문에
// 원본 state를 복사한뒤 action 객체를 추가해서 return한다.
return [...state, action.payload];
case "DELETE_CART" :
return action.payload;
default :
return state;
}
}
export default cartReducer;
dispath
로 action
객체를 매개변수로 전달받으면 해당 reducer
가 실행된다.initialstate
는 reducer
의 매개변수로 state
값이 전달되지 않았을때 정의해준 데이터를 넣는다는 뜻이다.import { combineReducers } from "redux";
import cartReducer from "./cartReducer";
import cartReducer from "./productReducer";
export default combineReducers({ cartReducer, productReducer });
여러 reducer
들을 combineReducers
라는 hook
을 사용해 하나로 묶어서 export
한다.