gpt4 book ai didi

angular - NgRx reducer 中的拼接索引不会删除一个索引

转载 作者:行者123 更新时间:2023-12-02 00:10:29 26 4
gpt4 key购买 nike

我尝试使用 NgRx v8 和操作分派(dispatch)删除数组中的一个索引,但它删除了除数组中第一项之外的所有数组。

我尝试从我的数组中删除 1 个项目,但它不起作用。

Reducer:
import { Comment } from '../models/comment.model';
import * as CommentAction from '../actions/comment.actions';
import { Action, createReducer, on } from '@ngrx/store';

export const initialState: Comment[] = [];

const commentReducer = createReducer(
initialState,
on(CommentAction.addcomment, (state, { fullName, comment }) => [...state, { fullName, comment }]),
on(CommentAction.removecomment, (state, { index }) => state.splice(index, 1))
);

export function reducer(state: Comment[], action: Action) {
return commentReducer(state, action);
}

Action

import { createAction, props } from '@ngrx/store';
import { Comment } from '../models/comment.model';

export const addcomment = createAction(
'[COMMENT] Add',
props<Comment>()
);

export const removecomment = createAction(
'[COMMENT] Remove',
props<{ index: number }>()
);

组件:

  delComment(i) {
this.store.dispatch(removecomment({index: i}));

}

html:

<div class="right" *ngIf="comment$">
<h3>Comment</h3>
<!-- <ul> -->
<li (click)="delComment(i)" *ngFor="let comm of comment$ | async; let i = index">
<p> Name: {{comm.fullName}}</p>
<p> Comment: {{comm.comment}}</p>
<!-- </li>
</ul> -->
</div>

最佳答案

这是因为 splice 不会返回没有删除项的数组,而是返回由删除项组成的数组:)

要让它工作,你应该这样做:

on(CommentAction.removecomment, (state, { index }) => {
const array = [...state];
array.splice(index, 1);
return array;
})

关于angular - NgRx reducer 中的拼接索引不会删除一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59304895/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com