Как обновить один объект в массиве объектов? - PullRequest
1 голос
/ 24 октября 2019

Я делаю простое приложение для адресной книги с использованием response-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,
            };
        });
    }

Ответы [ 2 ]

1 голос
/ 24 октября 2019

Попробуйте это:

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
    });
}
0 голосов
/ 25 октября 2019

Это мое решение, которое сработало. Спасибо всем, кто предложил свои ответы.

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