admin 管理员组文章数量: 1086019
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). The newAppt never gets added to the state.
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": []
};
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). The newAppt never gets added to the state.
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": []
};
Share
Improve this question
asked Jun 30, 2018 at 22:02
allencodedallencoded
7,29517 gold badges75 silver badges133 bronze badges
1
- 1 What does your state look like exactly? Is object-rest-spread supported in your browser (or are you using a babel plugin for it)? – Damon Commented Jun 30, 2018 at 22:08
2 Answers
Reset to default 4Many 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. 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
. Just go with:
this.setState({ ...this.state.appointmentsData, newAppt});
. It seems to me that the spread operator on newAppt
is not getting any data for the const
.
本文标签: javascriptSetState in an array with React spread operatorStack Overflow
版权声明:本文标题:javascript - SetState in an array with React spread operator - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744096152a2532934.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论