๊ธฐ์กด์ Redux ์ฝ๋๋ฅผ ์กฐ๊ธ ๋ ๊ฐ์ํ ํ ์ ์์
Redux ์ธ์ ์ค์นํด์ผ ํ๋ ๊ฐ์ข ํจํค์ง ๊ธฐ๋ฅ์ ๋ด์ฅํ๊ณ ์์ด, ๋ ๊ฐํธํ๊ฒ ๋ค์ํ ํจํค์ง ๊ธฐ๋ฅ์ ์ฌ์ฉํ ์ ์๋๋ก ๋์
$ yarn add @reduxjs/toolkit react-redux
๊ธฐ์กด Reducer์์ฑ๋ฐฉ์
//์ก์
ํ์
์์ฑ
export const INC_COUNT = 'counter/INC_COUNT'
//์ก์
์์ฑํจ์
const increase = () => {
return {
type: INC_COUNT,
}
}
//์ด๊ธฐ๊ฐ
const initialState = 0
//๋ฆฌ๋์
export default function couter(state = initialState, action) {
switch (action.type) {
case INC:
return state + 1
}
}
createAction
์ผ๋ก ์กฐ๊ธ ๋ ๊ฐํธํ๊ฒ action์ ์ ์createReducer
๋ก switch๋ฌธ์ ์ฌ์ฉํ ํ์ ์์ด ๊ฐ๊ฒฐํ๊ฒ ์์ฑtoolkit์ ํ์ฉํ Reducer์์ฑ๋ฐฉ์
import { createAction, createReducer } from "@reduxjs/toolkit";
// ์ก์
์์ฑ
export const increase = createAction('counter/increase')
//์ด๊ธฐ๊ฐ
const initialState = 0
//๋ฆฌ๋์
const counter = createReducer(initialState, {
[increase] : (state,action) => state + 1
})
export default counter
createStore
๊ฐ ์๋ configureStore
๋ก store๋ฅผ ์์ฑimport { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterReducer'
const store = configureStore({
reducer: counterReducer
})
combineReducers
์ฌ์ฉimport { combineReducers, configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterReducer'
import postReducer from './postReducer'
const rootReducer = combineReducers({
counter: counterReducer,
post: postReducer
})
const store = configureStore({
reducer: rootReducer
})
createAction
๊ณผ createReducer
๋ฅผ ํ๋์ ํจ์๋ก ํตํฉํ์ฌ ์ฌ์ฉํ๋ ๋ฐฉ์์ฌ๋ผ์ด์ค ์ด๋ฆ.actions
, ์ฌ๋ผ์ด์ค ์ด๋ฆ.reducers
์ผ๋ก ๊ฐ ์ก์
๋ค๊ณผ ๋ฆฌ๋์๋ฅผ ๊บผ๋ด์ฌ ์ ์๋ค//counterSlice.js
import { createSlice } from "@reduxjs/toolkit";
const initialState = 0;
counterSlice = createSlice({
name: counter,
initialState,
reducers: {
increase: (state) => state + 1,
decrease: (state) => state - 1,
}
})
export const { increase, decrease } = counterSlice.actions;
export default counterSlice.reducer;
//store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice'
const store = configureStore({
reducer: counterReducer
})