【发布时间】:2020-08-31 14:13:21
【问题描述】:
我正在开发一个在 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 这样的任务正在做状态突变,这不好。我想用 readonly 声明我的状态接口以避免状态突变。我已经经历了Redux-Toolkit-Usage-With-Typescript,我认为应该避免状态突变,但所有代码 sn-ps 似乎都在进行状态突变。我想要这样的东西
entityFetched: (state, action) => {
return {
...state,
actionsLoading:false,
entityForEdit:action.payload.entityForEdit,
error:null
}
}
如果我遗漏了什么或误解了状态突变的含义,请指导我。 任何关于将 TypeScript 与 React 结合使用的更广泛的建议都将受到欢迎! 非常感谢!
【问题讨论】:
标签: javascript reactjs typescript redux redux-toolkit