我正在使用react-bootstrap创建一个简单的通讯簿应用程序。我已经成功实现了添加新联系人或删除现有联系人的方法,但是在更新现有联系人时遇到了问题。截至目前,当我按下“编辑”按钮更新联系人时,将添加具有“更新”信息的新联系人,而不是替换所选联系人。我的联系人存储在称为“人”的对象数组中
这是我的完整源代码: https://github.com/DeonChoi/address-book
constructor(props){
super(props);
this.state = {
show: false,
people: [],
firstName: '',
lastName: '',
address: '',
city: '',
country: '',
postalCode: null,
phone: null,
email: '',
age: null
};
this.editPerson = this.editPerson.bind(this);
}
editPerson = (index) => {
this.setState(state => {
const people = state.people.map((person, personIndex) => {
if (personIndex === index) {
person.newFirstName = this.state.firstName;
person.newLastName = this.state.lastName;
person.newAddress = this.state.address;
person.newCity = this.state.city;
person.newCountry = this.state.country;
person.newPostalCode = this.state.postalCode;
person.newPhone = this.state.phone;
person.newEmail = this.state.email;
person.newAge = this.state.age;
return person;
} else {
return person;
}
});
return {
people,
};
});
}
答案 0 :(得分:1)
尝试一下:
editPerson = index => {
let {people} = this.state;
let peopleArr = people.slice();
let user = peopleArr[index];
user.newFirstName = this.state.firstName;
user.newLastName = this.state.lastName;
user.newAddress = this.state.address;
user.newCity = this.state.city;
user.newCountry = this.state.country;
user.newPostalCode = this.state.postalCode;
user.newPhone = this.state.phone;
user.newEmail = this.state.email;
user.newAge = this.state.age;
peopleArr[index] = user;
this.setState({
people: peopleArr
});
}
答案 1 :(得分:-1)
这是我有效的解决方案。感谢所有提出自己答案的人。
editPersonIndex = (index) => {
this.setState({
personID: index
})
}
editPerson = (index) => {
this.setState(state => {
const people = state.people.map((person, personIndex) => {
if (personIndex === index) {
person.newFirstName = this.state.firstName;
person.newLastName = this.state.lastName;
person.newAddress = this.state.address;
person.newCity = this.state.city;
person.newCountry = this.state.country;
person.newPostalCode = this.state.postalCode;
person.newPhone = this.state.phone;
person.newEmail = this.state.email;
person.newAge = this.state.age;
return person;
} else {
return person;
}
});
return {
people,
};
});
}