需要一些帮助...如何更新状态以反映新时间表(按ID)添加到特定孩子?
我目前有一个表单,该表单提供了一组看起来像这样的新数据(表单中的值在空字符串中):
{
date: '',
parent: '',
activity: ''
}
我已经在下面创建了此函数,然后将其传递给孩子的id
,并传递了新的时间表,该时间表类似于上面的时间表... >
addSched = (id, schedule) => {
const newSched = this.state.children.map(child => {
if (child.id !== id) return child;
return {
...child,
schedules: schedule
};
});
this.setState({ children: newSched });
};
我当前的状态如下:
state = {
children: [
{
id: 1,
firstName: 'Bella',
lastName: 'Laupama',
schedules: [
{
id: 1,
date: '25 December 2018',
parent: 'Chris',
activity: 'Christmas'
},
{
id: 2,
date: '31 December 2018',
parent: 'Laura',
activity: 'New Years Eve'
}
]
},
{
id: 2,
firstName: 'Cara',
lastName: 'Malane',
schedules: [
{
id: 1,
date: '25 December 2018',
parent: 'Chris',
activity: 'Christmas'
} ...etc
具有该形式的组件具有以下内容:
export default class AddSched extends React.Component {
state = {
date: '',
parent: '',
activity: ''
}
handleChange = e => {
this.setState({
[e.target.name]: e.target.value
})
}
submitHandler = e => {
e.preventDefault()
this.props.addSched(this.props.id, this.state)
console.log('SUBMITTED:', this.state)
this.setState({
date: '',
parent: '',
activity: ''
})
}
答案 0 :(得分:1)
您可以使用数组扩展运算符来连接现有数组和新计划:
schedules: [...child.schedules, schedule]
具有更改的完整功能:
ddSched = (id, schedule) => {
const newSched = this.state.children.map(child => {
if (child.id !== id) return child;
return {
...child,
schedules: [...child.schedules, schedule]
};
});
this.setState({ children: newSched });
};