简体   繁体   中英

I am trying to add an object to a nested array I have stored in my state object, but seem to have an issue with it

I have an object which I have created in state and it is my model for the booking. My addPassenger function should when click create an empty object into array with properties. When I console.log the new array it returns me the array properly but when I execute function nothing happens, no error. Just blank console.

My whole component https://pastebin.com/RLprKJrr

 booking: {
        id: "",
        number: "",
        date: "",
        bookingStatus: "OPCIJA",
        paymentMethod: "MODELA1",
        tripID: 1,
        passengers: [
          {
            id: "",
            holder: {
              email: "",
              address: "",
              mobile: ""
            },
            name: "",
            surname: "",
            passport: "",
            idCard: ""
          }
        ]
      }

addPassenger = e => {
    e.preventDefault();
    let passengersArray = [...this.state.booking.passengers];
    console.log(passengersArray);
    this.setState({
      passengers: [...passengersArray, {
        id: "", 
        name: "",
        surname: "",
        passport: "",
        idCard: ""
      }]
    })
    this.checkArrayLength();
  }

Because the problem is with data being passed to setState

This is the structure of your initial state

{
  booking: {
    passengers: {
      ...
    }
  }
}

Which is then accessible through this.state.booking.passengers

But when you are setting state again, you are putting passengers on same level as bookings like this

{
   booking: {
     ...
   },
   passengers: {
     ...
   }
 }

So you basically need to do this

this.setState({
  bookings: {
    ...this.state.bookings,
    passengers: [...passengersArray, {
        id: "", 
        name: "",
        surname: "",
        passport: "",
        idCard: ""
      }]
  }
})

Please try to set state of booking.passengers, not just passengers:

this.setState({
  booking.passengers: ...

You have to include the key 'booking' in your new state:

this.setState(previousState => ({
  booking: {
    ...previousState.booking,
    passengers: [...passengersArray, {
      id: "", 
      name: "",
      surname: "",
      passport: "",
      idCard: ""
    }]
  }
}));

I hope it helps you!

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