Javascript 使用调度时,ngrx从列表中删除项目
我有一份申请。我正在使用ngrx进行状态管理 但问题是,如果我试图删除该项,它将重定向到其他选项卡。并且不删除项目 所以我有这个: 减速器:Javascript 使用调度时,ngrx从列表中删除项目,javascript,angular,typescript,rxjs,ngrx,Javascript,Angular,Typescript,Rxjs,Ngrx,我有一份申请。我正在使用ngrx进行状态管理 但问题是,如果我试图删除该项,它将重定向到其他选项卡。并且不删除项目 所以我有这个: 减速器: const intialState: Tutorial = { name: 'initial State', url: 'http://google.com' }; export function tutorialReducer(state: Tutorial[] = [intialState], action: TutorialActions.
const intialState: Tutorial = {
name: 'initial State',
url: 'http://google.com'
};
export function tutorialReducer(state: Tutorial[] = [intialState], action: TutorialActions.Actions) {
switch (action.type) {
case TutorialActions.ADD_TUTORIAL:
return [...state, action.payload];
case TutorialActions.DELETE_TUTORIAL:
state.splice(action.payload, 1);
return state;
default:
return state;
}
}
行动:
export class AddTutorial implements Action {
readonly type = ADD_TUTORIAL;
constructor(public payload: Tutorial) {}
}
export class RemoveTutorial implements Action {
readonly type = DELETE_TUTORIAL;
constructor(public payload: number) {}
}
export type Actions = AddTutorial | RemoveTutorial;
并删除模板:
<div class="right" *ngIf="tutorials$">
<h3>Tutorials</h3>
<ul>
<li (click)="delTutorial(i)" *ngFor="let tutorial of tutorials$ | async; let i = index">
<a [href]="tutorial.url" target="_blank">{{ tutorial.name }}</a>
</li>
</ul>
</div>
但它不会删除该项,但实际上会打开一个新选项卡
然后我得到这个错误:
core.js:9110 ERROR TypeError: Cannot assign to read only property '5' of object '[object Array]'
at Array.splice (<anonymous>)
at tutorialReducer (tutorial.reducers.ts:16)
at combination (store.js:303)
at store.js:1213
at store.js:38
core.js:9110错误类型错误:无法分配给对象“[object Array]”的只读属性“5”
在Array.splice()处
在tutorialReducer(tutorial.reducers.ts:16)
at组合(store.js:303)
在商店。js:1213
在商店。js:38
那么我要改变什么呢?以便您可以从列表中删除项目
谢谢你我建议你做以下几件事:
- 你应该避免直接改变状态
- 创建状态的副本,然后执行该操作
- 还要记住的是,splice将第一个参数作为要删除的元素的索引
- 从数组中查找有效负载或项目的索引
- 然后使用此索引拼接阵列元素
- 例如:
我希望这些观点对您有所帮助。状态是不变的。因此,无法更改减速器中的状态。 必须在不更改当前状态的情况下返回新的修改值
case TutorialActions.DELETE_TUTORIAL:
let newState = [...state];
newState.splice(action.payload, 1);
return newState;
非常感谢。很不错的。我只给一个答案打分数。但我投票支持你我感谢你的考虑
core.js:9110 ERROR TypeError: Cannot assign to read only property '5' of object '[object Array]'
at Array.splice (<anonymous>)
at tutorialReducer (tutorial.reducers.ts:16)
at combination (store.js:303)
at store.js:1213
at store.js:38
var array = [...state]; // make a separate copy of the array or state
var index = array.indexOf(your_payload_toberemoved)
if (index !== -1) {
array.splice(index, 1);
return array
}
case TutorialActions.DELETE_TUTORIAL:
let newState = [...state];
newState.splice(action.payload, 1);
return newState;