Redux는 state를 효율적으로 관리하기 위한 라이브러리입니다.
모든 컴포넌트가 공유할 수 있는 보관소인 redux store에 state를 보관하여 필요한 곳에서 가져다 사용할 수 있습니다.
Redux로 state를 사용하는 방법은 아래와 같습니다.
1. createSlice() 함수로 state 생성
(store.js)
import { configureStore, createSlice } from '@reduxjs/toolkit';
// 1. createSlice()로 state 만들기
let user = createSlice({
name: 'user',
initialState: 'kim'
});
먼저, store.js 파일에서 createSlice 함수를 사용하여 원하는 state를 생성합니다.createSlice는 두 가지 매개변수를 받습니다.name은 생성되는 state의 이름을 지정하고, initialState는 초기 상태 값을 설정합니다.{ name : 'state이름', initialState : 'state값' }
2. configureStore() 함수로 state 등록
(store.js)
import { configureStore, createSlice } from '@reduxjs/toolkit';
let user = createSlice({
name: 'user',
initialState: 'kim'
});
// 2. configureSotre()안에 등록하기
export default configureStore({
reducer: {
user: user.reducer
}
});
원하는 state를 생성했다면, 다음은 state를 등록합니다.configureStore() 함수 안에 state를 등록할 수 있으며, 등록할 때는 { 작명: createSlice만든거.reducer } 형식으로 작성합니다. 여기에 등록한 state는 모든 컴포넌트는 자유롭게 사용할 수 있습니다.
3. useSelector() 훅을 활용하여 state 가져다 쓰기
(Cart.js)
import { useSelector } from "react-redux";
function Cart() {
let a = useSelector((state) => { return state; });
console.log(a); // 출력 결과 예시: { user : 'kim' }
return (
// 생략
);
}
먼저 useSelector를 import하고, state를 사용하고 싶은 곳에서 useSelector((state) => { return state; })와 같이 사용하면 Redux store에 있는 모든 state가 해당 위치에 남아있게 됩니다.
let a = useSelector((state) => state.user )
4. 실습
[
{id : 0, name : 'White and Black', count : 2},
{id : 2, name : 'Grey Yordan', count : 1}
]
위 데이터를 redux store에 보관해두고 가져다 사용해보겠습니다.
1. state 생성 및 등록
(store.js)
// state 생성
let cart = createSlice({
name : 'cart',
initialState : [
{ id: 0, name: 'White and Black', count: 2 },
{ id: 2, name: 'Grey Yordan', count: 1 },
]
})
// state 등록
export default configureStore({
reducer: {
cart: cart.reducer
},
});
2. state 사용
import { Table } from 'react-bootstrap'
// useSelector 임포트
import { useSelector } from "react-redux"
function Cart(){
// state 가져와서 변수에 저장
let state = useSelector((state) => {return state})
return (
<Table>
<thead>
<tr>
<th>#</th>
<th>상품명</th>
<th>수량</th>
<th>변경하기</th>
</tr>
</thead>
<tbody>
// 원하는 곳에 사용 + map으로 코드 확장성
{state.cart.map((a, i) => {
return(
<tr key={i}>
<td>{state.cart[i].id}</td>
<td>{state.cart[i].name}</td>
<td>{state.cart[i].count}</td>
<td><button>+</button></td>
</tr>)
})}
</tbody>
</Table>)
}
export default Cart;
'React' 카테고리의 다른 글
React 쇼핑몰(if문 작성 패턴) (1) | 2023.10.28 |
---|---|
React 쇼핑몰(Redux: object/array 변경) (1) | 2023.10.27 |
React 쇼핑몰(Redux: 설치 및 세팅) (0) | 2023.10.25 |
React 쇼핑몰(Context API) (0) | 2023.10.24 |
React 쇼핑몰(transition 애니메이션) (1) | 2023.10.24 |