[英]Redux-toolkit usage with Typescript without state mutation
我正在開發一個在 JavaScript 中使用Redux-Toolkit的 React 項目。我正在嘗試將項目轉移到 TypeScript 以獲得調試便利和類型安全優勢。 我的切片代碼是
export const entitiesSlice = createSlice({
name: "entities",
initialState: initialentitiesState,
reducers: {
// getentityById
entityFetched: (state, action) => {
state.actionsLoading = false;
state.entityForEdit = action.payload.entityForEdit;
state.error = null;
},
// findentities
entitiesFetched: (state, action) => {
const { totalCount, entities } = action.payload;
state.listLoading = false;
state.error = null;
state.entities = entities;
state.totalCount = totalCount;
},
// createentity
entityCreated: (state, action) => {
state.actionsLoading = false;
state.error = null;
state.entities.push(action.payload.entity);
},
// updateentity
entityUpdated: (state, action) => {
state.error = null;
state.actionsLoading = false;
state.entities = state.entities.map(entity => {
if (entity.id === action.payload.entity.id) {
return action.payload.entity;
}
return entity;
});
},
// deleteentities
entitiesDeleted: (state, action) => {
state.error = null;
state.actionsLoading = false;
state.entities = state.entities.filter(
el => !action.payload.ids.includes(el.id)
);
},
}
}
});
但我認為像這樣的分配state.somevar=updatedval
正在做 state 突變這不好。 我想用 readonly 聲明我的 state 接口以避免 state 突變。 我已經完成了Redux-Toolkit-Usage-With-Typescript ,我認為它應該避免 state 突變,但所有代碼片段似乎都在做 state 突變。 我想要這樣的東西
entityFetched: (state, action) => {
return {
...state,
actionsLoading:false,
entityForEdit:action.payload.entityForEdit,
error:null
}
}
如果我遺漏了什么或誤解了 state 突變的含義,請指導我。 任何關於將 TypeScript 與 React 一起使用的更廣泛的建議將是最受歡迎的! 多謝!
Redux Toolkit 的createReducer
和createSlice
API 在內部使用Immer 庫,它允許您在 reducer 中編寫“可變”語法,但將其轉換為安全且正確的不變更新。
請通讀新的“Redux Essentials”核心文檔教程,以進一步解釋 Redux 如何依賴不變性,以及 Immer 如何確保在 reducer 中安全地編寫“突變”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.