【问题标题】:ngrx removing item from list when using dispatchngrx 使用调度时从列表中删除项目
【发布时间】:2020-08-07 21:50:38
【问题描述】:

我有 Angular 8 应用程序。我正在使用 ngrx 进行状态管理。

但问题是,如果我尝试删除项目,它将重定向到其他选项卡。而不是删除项目。

所以我有这个:

减速器:

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>

和ts代码:

export class ReadComponent implements OnInit {

  tutorials$: Observable<Tutorial[]>;

  constructor(private store: Store<AppState>) {
  this.tutorials$ = this.store.select('tutorial');
  }

 delTutorial(index){
    this.store.dispatch(new TutorialActions.RemoveTutorial(index));
  }
  ngOnInit() {
  }

}

和 app.module.ts:

 imports: [
    BrowserModule,
    StoreModule.forRoot({tutorial: tutorialReducer}),
    AppRoutingModule
  ],

但是它并没有删除项目,而是实际上打开了一个新标签。

然后我得到这个错误:

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

那么我必须改变什么?这样您就可以从列表中删除一个项目?

谢谢

【问题讨论】:

    标签: javascript angular typescript rxjs ngrx


    【解决方案1】:

    我推荐以下几点:

    • 您应该避免直接改变状态。
    • 创建状态副本,然后执行操作
    • 还要记住一点,splice 将第一个参数作为您要删除的元素的索引。
    • 从数组中找到有效载荷或项的索引
    • 然后用这个索引拼接数组元素。

    • 例如:

    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
      }   
    

    希望这些要点对您有所帮助。

    【讨论】:

    • 谢谢。很不错。我只是给一个解决方案打分。但我投了你一票
    • 感谢您的考虑@savantTheCoder
    【解决方案2】:

    状态是不可变的。因此,您无法更改减速器中的状态。 您必须在不更改当前状态的情况下返回一个新的修改值。

    case TutorialActions.DELETE_TUTORIAL:
      let newState = [...state]; 
      newState.splice(action.payload, 1);
      return newState;
    

    【讨论】:

      猜你喜欢
      • 2017-12-28
      • 1970-01-01
      • 2022-12-20
      • 2012-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-08
      相关资源
      最近更新 更多