问题描述
我正在研究一个React项目,该项目在JavaScript中使用Redux-Toolkit。我正在尝试将项目转移到TypeScript,以简化调试并获得Type Safety的好处。我的切片代码为
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
分配正在做状态突变,这不好。我想用只读声明状态接口,以避免状态突变。我经历过Redux-Toolkit-Usage-With-Typescript,我认为应该避免状态突变,但是所有代码片段似乎都在进行状态突变。我想要这样的东西
entityFetched: (state,action) => {
return {
...state,actionsLoading:false,entityForEdit:action.payload.entityForEdit,error:null
}
}
如果我缺少某些东西或误解了状态突变的含义,请指导我。 任何将TypeScript与React一起使用的更广泛的建议都将受到欢迎! 非常感谢!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)