繁体   English   中英

拼接仅删除数组中的最后一个元素

[英]Splice removes only last element in array

我在React上遇到了一个小问题(仍然是个新问题)。 我有一系列结果。 这些结果将预订嵌套在一个数组中,而后者正是我要处理的。

当用户创建预订时,一切都按预期进行findIndex获取正确的Result元素并相应地修改其Bookings数组。

但是,当我想“取消预订”时,它仅找到数组中的最后一个Result,而findIndex始终为-1 (因此我什至没有进入Bookings部分,因为我得到的Result索引是错误的)。

代码相似,我的商品都有唯一的键,我不明白可能是什么问题(使用Alt作为Flux实现)?

这是在Create上发生的事情:

onCreateBookingSuccess(data) {
    let resultIndex = this.results.findIndex((result) => result.id === data.id);
    this.results.update(resultIndex, (result) => result.bookings.push(data));
    toastr.info('Booked! User will receive notification.');
  }

并删除:

onDestroyBookingSuccess(data) {
    let resultIndex = this.results.findIndex((result) => result.id === data.id);
    var myBooking;
    this.results.map((result) => {
      myBooking = result.bookings.findIndex((booking) => booking.id === data.booking);
    });
    this.results.update(resultIndex, (result) => result.bookings.splice(myBooking,1));
    toastr.warning('Unbooked! User will receive notification.');
  }

我的对象:

<Result key={result.id} id={result.id} bookings={result.bookings} />

正如我所提到的,第一个操作按计划进行,一切都按需进行了修改。 第二个操作的问题从一开始就开始,当resultIndex返回-1

问题似乎在这里:

var myBooking;
this.results.map((result) => {
  myBooking = result.bookings.findIndex((booking) => booking.id === data.booking);
});

即使已找到索引( -1 ),也始终要分配给myBooking ,因此它等效于this.results.last().bookings.findIndex(...) 真的,您只想获得不为-1的(first?)值:

var myBooking = this.results.map((result) => {
  myBooking = result.bookings.findIndex((booking) => booking.id === data.booking);
}).find((index) => index != -1);

另外,请考虑重命名myBooking以更好地表明它是索引而不是实际记录。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM