Web/React
React - Redux Toolkit
또롱또
2022. 5. 26. 19:20
728x90
툴킷에 대해 공식문서 예제로 설명을 하려한다.
https://redux-toolkit.js.org/tutorials/quick-start
1. store를 생성해준다
import { configureStore } from '@reduxjs/toolkit'
// 빈 스토어 생성,
// configureStore - reducer에서 반환된 새로운 state를 store라는 객체로 정리
export const store = configureStore({
reducer: {},
})
2. store를 index.js에 연결해준다 - 전역관리 세팅
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import { store } from './app/store'
import { Provider } from 'react-redux'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Provider store={store}>
<App />
</Provider>
);
3. 내가 전역으로 관리할 데이터 스크립트를 만든다
import { createSlice } from '@reduxjs/toolkit'
// 초기값 설정
const initialState = {
value: 0,
}
// createSlice - state의 초기값들과 action creator와 reducer를 생성해준다.
export const counterSlice = createSlice({
name: 'counter', // 이 모듈의 이름
initialState, // 이 모듈의 초기값
reducers: { // 리듀서의 키값으로 action함수가 자동생성
increment: (state) => {
state.value += 1
},
decrement: (state) => {
state.value -= 1
},
incrementByAmount: (state, action) => {
state.value += action.payload
},
},
})
// 위에서 생성한 reducer의 키값을 export해준다 다른데서 가져가서 action을 취할수 있게
export const { increment, decrement, incrementByAmount } = counterSlice.actions
// reducer를 밖으로 빼서 사용할수있게
export default counterSlice.reducer
4. store.js에 아까만든 reducer를 채워준다
import { configureStore } from '@reduxjs/toolkit'
import counterReducer from '../features/counter/counterSlice'
export const store = configureStore({
reducer: {
// 리듀서에 주어진 이름에 받아온 리듀서를 채워준다.
counter: counterReducer,
},
})
// 여기까지되면 전역으로 관리하고 싶은 애가 store안에 생성된다.
5. 불러서 쓰기
import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { decrement, increment } from './counterSlice'
export default function Counter() {
// store가 한개뿐이니;까 store를 돌면서 원하는 reducer 이름의 값을 꺼내온다
const count = useSelector((state) => state.counter.value)
// 수정하고싶을때는 그냥 useDispatch를 이용한다 - 그냥 외우자
const dispatch = useDispatch()
return (
<div>
<div>
<button
aria-label="Increment value"
// reducer에서 action을 가져와서 이렇게 한다.
onClick={() => dispatch(increment())}
>
Increment
</button>
{/* 내가 가져와서 보여주고싶은 값은 이렇게 사용 */}
<span>{count}</span>
<button
aria-label="Decrement value"
onClick={() => dispatch(decrement())}
>
Decrement
</button>
</div>
</div>
)
}
728x90