簡體   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