[英]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.
我的addPassenger函数应该在单击时使用属性创建一个空对象到数组中。 When I console.log the new array it returns me the array properly but when I execute function nothing happens, no error.
当我在console.log中新建数组时,它会正确返回数组但是当我执行函数时没有任何反应,没有错误。 Just blank console.
只是空白控制台。
My whole component https://pastebin.com/RLprKJrr 我的整个组件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
因为问题是将数据传递给
setState
This is the structure of your initial state 这是您初始状态的结构
{
booking: {
passengers: {
...
}
}
}
Which is then accessible through this.state.booking.passengers
然后可以通过
this.state.booking.passengers
访问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: 请尝试设置booking.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! 我希望它对你有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.