【发布时间】:2018-12-13 20:46:29
【问题描述】:
React 新手搞砸了,抱歉,但真的尝试了好几个小时;(请参阅下面的尝试。
简单任务:尝试更新对象数组中的对象。
这应该很容易,尽管在研究了十几个答案之后,尝试了一堆可能的解决方案,但我仍然会出错。我无法弄清楚我在这里缺少什么。
这是我的 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”来自另一个组件,其中包含一个表单并处理 onSubmit 这个函数:
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);
};
非常感谢您的帮助!
【问题讨论】:
标签: javascript reactjs object filter find