我有这样的 this.props.person :
person = [{id: 1, name: John, age: 20},
{id: 2, name: Kate, age: 30},
{id: 3, name: Mike, age: 25}]
我有空的 this.state.newPerson: []。
函数获取id值,在this.props.person中搜索具有该id的对象,并将该对象添加到this.state.newPerson中。可以重复几次。
例如:我使用 id=1 和 id=3 调用函数 addPerson 两次。结果我应该得到
this.state.newPerson: [{id: 1, name: John, age: 20}, {id: 3, name: Mike, age: 25}].
我尝试过:
addPerson(idPerson) {
const list = this.state.newPerson;
const personToList = this.props.person.find(el => el.id === idPerson);
const newP = Object.assign(list, { personToList });
this.setState({ newPerson: newP });
}
事实上,我得到了类似 [personToList {id: ...}]
的内容如何修复它?
最佳答案
如果 this.state.newPerson 是一个数组,为什么还要使用 Object.assign ?
只需使用
list.push(personToList)
但像这样设置你的状态 this.state.newPerson = [];
关于javascript - 在 React 中将对象从一个对象数组复制到另一个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53031248/