本來想學習Redux in ReactJs,卻被它的語法難倒。
export const counterSlice = createSlice({ name: 'counter', initialState: { value: 0 }, reducers: { increment: state => { // Redux Toolkit allows us to write "mutating" logic in reducers. It // doesn't actually mutate the state because it uses the Immer library, // which detects changes to a "draft state" and produces a brand new // immutable state based off those changes state.value += 1 }, decrement: state => { state.value -= 1 }, incrementByAmount: (state, action) => { state.value += action.payload } } })
在我比較熟悉的Pinia其實有也類似的語法。
export const useCounterStore = defineStore('counter', { state: () => ({ count: 0, }), getters: { // type is automatically inferred because we are not using `this` doubleCount: (state) => state.count * 2, // here we need to add the type ourselves (using JSDoc in JS). We can also // use this to document the getter /** * Returns the count value times two plus one. * * @returns {number} */ doubleCountPlusOne() { // autocompletion ✨ return this.doubleCount + 1 }, }, })
因為Pinia比較簡單,我只要知道在state, getters, actions裡放對東西就行,但我知道其實是Pinia在底層簡化了很多東西,卻不知道怎麼運作,到Redux上以乎不理解不行,最後被卻這篇教學搞傻了The simplest way to combine React, Redux and Firestore (Typescript),放棄ReactJs改回熟悉的VueJS來開發Side Project。
import { ActionCreatorWithOptionalPayload, ActionCreatorWithoutPayload, createSlice, PayloadAction, SliceCaseReducers, ValidateSliceCaseReducers } from '@reduxjs/toolkit'; export const createGenericSlice = < T, Reducers extends SliceCaseReducers<GenericState<T>> >({ name = '', initialState, reducers }: { name: string; initialState: GenericState<T>; reducers: ValidateSliceCaseReducers<GenericState<T>, Reducers>; }) => { return createSlice({ name, initialState, reducers: { loading(state) { state.status = StateStatus.Loading; }, success(state: GenericState<T>, action: PayloadAction<T>) { state.data = action.payload; state.status = StateStatus.Done; }, error(state: GenericState<T>, action: PayloadAction<any>) { state.status = StateStatus.Error; }, ...reducers // <----------------- 究竟這裡的...是什麼意思啊~~~~~~~~~~~~~~~ } }); };
結果卻在我重構公司的項目時,竟然逐步走向這種語法,最終完全明白了這種語法背後的演變,本文將講解這演變的過程。