gpt4 book ai didi

javascript - 如何从状态内更新对象内的数组?

转载 作者:行者123 更新时间:2023-11-29 23:13:32 27 4
gpt4 key购买 nike

需要一些帮助...我如何更新状态以反射(reflect)添加到特定 child 的新计划(按 ID)?

我目前有一个提供一组新数据的表单,如下所示(表单中的值在空字符串中):

{
date: '',
parent: '',
activity: ''
}

我在下面创建了这个函数,我将 child 的 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: ''
})
}

最佳答案

您可以使用数组展开运算符连接现有数组和新计划:

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 });
};

关于javascript - 如何从状态内更新对象内的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53389221/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com