Реагируют, что новичок все портит, извините, но действительно пытался часами; (см. Попытки ниже.
Простое задание: попытка обновить объект в массиве объектов.
Это должно быть довольно легко, хотя после исследования десятка ответов, пробуя кучу возможных решений, я все равно получаю ошибки. Я не могу понять, чего мне здесь не хватает.
Вот мои 4 попытки:
Попытка 1
updateText = (updatedText) => {
var arrTexts = {...this.state.arrTexts}
var myObjectToUpdate = arrTexts.filter(x => x.id === updatedText.id);
myObjectToUpdate = updatedText;
console.log (myObjectToUpdate);
console.log (arrTexts);
};
Попытка 2:
updateText = (updatedText) => {
var arrTexts = {...this.state.arrTexts}
var myObjectToUpdate = arrTexts.find(function (myObjectToUpdate) { return myObjectToUpdate.id === updatedText.id; });
myObjectToUpdate = updatedText
console.log (myObjectToUpdate);
console.log (arrTexts);
};
Попытка 3
updateText = (updatedText) => {
var arrTexts = {...this.state.arrTexts}
var myObjectToUpdate = arrTexts.findIndex(x => x.id === updatedText.id);
myObjectToUpdate = updatedText;
console.log (myObjectToUpdate);
console.log (arrTexts);
};
Попытка 4
updateText = (updatedText) => {
var arrTexts = {...this.state.arrTexts}
var myObjectToUpdate = _.findWhere(arrTexts, { id: updatedText.id });
myObjectToUpdate = updatedText;
console.log (myObjectToUpdate);
console.log (arrTexts);
};
«updateText» происходит из другого компонента, который включает форму и обрабатывает эту функцию:
handleUpdate = event => {
event.preventDefault();
const updatedText = {
...this.props.arrText,
id: this.idRef.current.value,
title: this.titleRef.current.value,
author: this.authorRef.current.value,
};
this.props.updateText(updatedText);
};
Большое спасибо за помощь!