reduxjs toolkit (RTK) actions vs reducers in createSlice fun


import { createSlice } from '@reduxjs/toolkit'
const initialState = { value: 0 }
const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment(state) {
state.value++
},
decrement(state) {
state.value--
},
incrementByAmount(state, action) {
state.value += action.payload
},
},
})
export const { increment, decrement, incrementByAmount } = counterSlice.actions
export default counterSlice.reducer

在导出时的最后第二行,为什么{increment, dec递减,incrementByAmount}从" counterslice .action "而不是"counterslice .reducers"?

//如果我遗漏了什么,请在评论中注明。;)由于

因为RTK会从您放入的所有reducer中生成一个reducer,然后自动为每个reducer生成一个action creator。

你必须区分"你在"以及"你得到了什么"这里-如果你想取出你输入的东西,你就不需要整个东西;)

因为createSlice()将返回如下对象:

export interface Slice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string> {
name: Name;
reducer: Reducer<State>;
actions: CaseReducerActions<CaseReducers>;
caseReducers: SliceDefinedCaseReducers<CaseReducers>;
getInitialState: () => State;
}

您可以在createSlice.d.ts文件中找到它,路径为:node_modules@reduxjstoolkitdistcreateSlice.d.ts

CaseReducerActions的动作键是对象包含动作{increment, decrement, incrementByAmount}

最新更新