Codemods
根據 1.9.0
中的說明,我們已在 RTK 2.0 主要版本中從 createReducer
和 createSlice.extraReducers
中移除「物件」引數。我們也新增了 createSlice.reducers
的新選用表單,它使用回呼而不是物件。
為了簡化程式碼庫的升級,我們已發布一組 Codemods,它將自動將已棄用的「物件」語法轉換為等效的「建構器」語法。
codemods 套件可在 NPM 上取得,網址為 @reduxjs/rtk-codemods
。目前包含下列 codemods
createReducerBuilder
:將使用已移除物件語法的createReducer
呼叫移轉至建構函式回呼語法createSliceBuilder
:將使用已移除物件語法的createSlice
呼叫移轉至建構函式回呼語法createSliceReducerBuilder
:將使用仍為標準物件語法的createSlice
呼叫移轉至可選的新建構函式回呼語法,包括使用已準備好的 reducer
若要對程式碼庫執行 codemods,請執行 npx @reduxjs/rtk-codemods <TRANSFORM NAME> path/of/files/ or/some**/*glob.js
。
範例
npx @reduxjs/rtk-codemods createReducerBuilder ./src
npx @reduxjs/rtk-codemods createSliceBuilder ./packages/my-app/**/*.ts
我們也建議在提交變更之前,重新對程式碼庫執行 Prettier。
這些 codemods 應該可以正常運作,但我們非常歡迎針對更多實際程式碼庫進行測試和提供回饋!
變更前
createReducer(initialState, {
[todoAdded1a]: (state, action) => {
// stuff
},
[todoAdded1b]: (state, action) => action.payload,
})
const slice1 = createSlice({
name: 'a',
initialState: {},
extraReducers: {
[todoAdded1a]: (state, action) => {
// stuff
},
[todoAdded1b]: (state, action) => action.payload,
},
})
變更後
createReducer(initialState, (builder) => {
builder.addCase(todoAdded1a, (state, action) => {
// stuff
})
builder.addCase(todoAdded1b, (state, action) => action.payload)
})
const slice1 = createSlice({
name: 'a',
initialState: {},
extraReducers: (builder) => {
builder.addCase(todoAdded1a, (state, action) => {
// stuff
})
builder.addCase(todoAdded1b, (state, action) => action.payload)
},
})