简体   繁体   中英

Splice removes only last element in array

I'm having a small issue with React (still new to it). I have an array of Results. These Results have nested Bookings, also in an array, and the latter is what I'm manipulating.

When User creates Booking, everything goes as expected - findIndex gets the correct Result element and modifies its Bookings array accordingly.

However, when I want to "Unbook", it only finds the last Result in the array, and findIndex is always -1 (so I haven't even gotten to the Bookings part, because the Result index I get is wrong).

The code is similar, my items all have unique keys, and I don't understand what could be the problem (using Alt as Flux implementation)?

Here is what happens on 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.');
  }

And on delete:

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.');
  }

My object:

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

As I mentioned, the first operation goes as planned, everything is modified as it should. The issue with the second op starts from the very beginning, when resultIndex returns -1 .

The problem seems to be here:

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

You're always assigning to myBooking , even when the index is not found ( -1 ) after having already found it, so it's equivalent to this.results.last().bookings.findIndex(...) . Really you only want to get the (first?) value that's not -1 :

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

Also, consider renaming myBooking to better indicate it's an index and not the actual record.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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