createSlice
리듀서 함수의 대상인 초기상태와 “슬라이스 이름”을 받아 리듀서와 상태에 해당하는 액션 생성자와 액션 타입을 자동으로 생성해 주는 함수.
const counterSlice = createSlice({
name: '', // 이 모듈의 이름
initialState : {}, // 이 모듈의 초기상태 값
reducers : {}, // 이 모듈의 Reducer 로직
})
initialState
: 이 모듈의 초기 생태 값
name
: 이 모듈의 이름
reducers
: 이 모듈의 Reducer 로직
import { createSlice } from '@reduxjs/toolkit'
const initialState = { number: 0 }
const counterSlice = createSlice({
name: "counter",
initialState,
reducers: {
// 리듀서 안에서 만든 함수 자체가 리듀서의 로직이자, 액션크리에이터가 된다.
addNumber: (state, action) => {
state.number = state.number + action.payload;
},
minusNumber: (state, action) => {
state.number = state.number - action.payload;
},
},
});
createSlice는 리듀스 로직이 되면서도 동시에 Action Creator 가 된다.
그리고 Action Value 까지 함수의 이름을 따서자동으로 만들어진다.