[英]SetState in an array with React spread operator
I have a value in my react state that looks like so: 我的反应状态中的值看起来像这样:
appointmentsData = {
"05-01-2018": [
{
id: "1",
friendly: "9:00am - 10:00am",
openDateTime: "9:00am",
closeDateTime: "10:00am"
}
]
};
I have a new piece of data: 我有一条新数据:
const newAppt = {"06-30-2018":[]}
How do I addon to my data in the state? 如何在状态中添加数据? I tried
我试过了
this.setState({ ...this.state.appointmentsData, ...newAppt});
It seems to no be adding onto state though. 似乎没有增加状态。 I get back the same value in the render as before (appointmentData before spread).
我在渲染中获得了与以前相同的值(散布之前为appointmentData)。 The newAppt never gets added to the state.
newAppt永远不会添加到状态中。
I am trying to get my states desired output to be: 我试图让我的状态期望的输出是:
appointmentsData = {
"05-01-2018": [
{
id: "1",
friendly: "9:00am - 10:00am",
openDateTime: "9:00am",
closeDateTime: "10:00am"
}
],
"06-30-2018": []
};
Many ways to do it, really. 确实有很多方法可以做到。 Here's one:
这是一个:
this.setState(prevState => (
{appointmentsData: {...prevState.appointmentsData}, newAppt}
));
Though your approach should work too, if you just add the appointmentsData:
first. 尽管您的方法也可以使用,但是如果您仅添加
appointmentsData:
Like so: 像这样:
this.setState({appointmentsData: {...this.state.appointmentsData, ...newAppt}});
This will spread all the previous values into a new object, plus the one you want to add. 这会将所有先前的值扩展到一个新对象,再加上要添加的对象。
I personally always use the functional way of setting the state when the new one depends on a previous state value, but your way is fine here too. 当新的状态依赖于先前的状态值时,我个人总是使用功能性的方式来设置状态,但是您的方法在这里也很好。
You should not use spread operator on newAppt
. 您不应在
newAppt
上使用传播运算符。 Just go with: this.setState({ ...this.state.appointmentsData, newAppt});
只需使用:
this.setState({ ...this.state.appointmentsData, newAppt});
. 。 It seems to me that the spread operator on
newAppt
is not getting any data for the const
. 在我看来,
newAppt
上的传播运算符未获取const
任何数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.