Trying to update object in array-6ren"> Trying to update object in array-React 新手把事情搞砸了,抱歉,但确实尝试了几个小时;(请参阅下面的尝试。 简单任务:尝试更新对象数组中的对象。 这应该相当容易,尽管在研究了十几个答案之后,尝试了一堆可能的解决方案,但我仍然遇到-6ren">
gpt4 book ai didi

javascript - react : "Error t.filter is not a function" or "Error: Uncaught TypeError: t.find is not a function" --> Trying to update object in array

转载 作者:行者123 更新时间:2023-12-03 01:33:27 25 4
gpt4 key购买 nike

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

非常感谢您的帮助!

最佳答案

filterfindfindIndex 都是适用于数组的函数。您的数据似乎是一个数组,但正在将其克隆到一个对象。您可以像 var arrTexts = [...this.state.arrTexts]

一样克隆它
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);
};

你也可以像这样更新它

handleUpdate = event => {
event.preventDefault();
const updatedText = {
id: this.idRef.current.value,
title: this.titleRef.current.value,
author: this.authorRef.current.value,
};
this.props.updateText(updatedText);
};

关于javascript - react : "Error t.filter is not a function" or "Error: Uncaught TypeError: t.find is not a function" --> Trying to update object in array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51190114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com