Redux 왜 씀?
ㄴ state를 한곳에 모아놓고 모든 컴포넌트가 state를 직접 꺼내쓸 수 있다
ㄴ props 없이도 편리하게 state 공유가 가능하다
ㄴ 컴포넌트가 많아질수록 관리가 용이해짐
여기서는 state 하나를 slice 라고 부른다
store.js
import { configureStore , createSlice } from '@reduxjs/toolkit'
let user = createSlice({
name : 'user' , // state 이름
initialState : 'kim' //state 값
});
createSlice()
createSlice()는 useState()랑 비슷한 용도.
createSlice() 안에는 객체로 넣어야함!!!
export default configureStore({
reducer: {
user : user.reducer
}
})
// 객체로 들어있으니까 안에서 콤마로 구분
state를 만들었다고 끝이아니고 이 안에 ★★등록★★해야 사용이 가능함!!!
Cart.js
import { useSelector } from "react-redux";
let state = useSelector((state)=>{return state.stock})
useSelector()
useSelector 가 store에서 꺼내와 주는 함수임.
useSelector 사용 팁 ☆☆☆☆☆
useSelector((state)=>{return state})
ㄴ 여기에서 리턴 되는 state는 store 안에있는 모든 state를 뜻함.
어떤 state를 가져오고 싶은지 return에 써줄수 있다!!
let userState = useSelector((state)=>{return state.user})
이런 식으로 가져오고 싶은 state만 따로 변수에 담을 수가 있음.
당연하지만 중괄호+return 생략 가능하다
useSelector(state => state.stock)
Cart.js
import { useSelector } from "react-redux";
function Cart(){
let cart = useSelector((state) => state.cart)
//중략 return Table
<tr>
<th>{cart[0].id}</th>
<th>{cart[0].name}</th>
<th>{cart[0].count}</th>
<th>변경하기</th>
</tr>
<tr>
<td>{cart[1].id}</td>
<td>{cart[1].name}</td>
<td>{cart[1].count}</td>
<td>변경하기</td>
</tr>
let cart = createSlice({
name : 'cart',
initialState : [
{id : 0, name : 'White and Black', count : 2},
{id : 2, name : 'Grey Yordan', count : 1}
]
})
상품 데이터가 이렇게 생겨서, 배열에서 먼저 꺼낸 다음에 객체로 들어가야 했다.
그리고 반복문 형태로 줄여도 봄.
<Table>
{
cart.map((_, i)=>{
return (
<tr>
<th>{cart[i].id}</th>
<th>{cart[i].name}</th>
<th>{cart[i].count}</th>
<th>변경하기</th>
</tr>
)
})
}
</Table>
잘 출력된다!