React: "Error t.filter is not a function" 或 "Error: Uncaught TypeError: t.find is not a function" --> 尝试更新数组中的对象

Yvo*_*onC 4 javascript object filter find reactjs

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);
};
Run Code Online (Sandbox Code Playgroud)

尝试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);
};
Run Code Online (Sandbox Code Playgroud)

尝试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);
};
Run Code Online (Sandbox Code Playgroud)

尝试4

updateText = (updatedText) => {

  var arrTexts = {...this.state.arrTexts}

  var myObjectToUpdate = _.findWhere(arrTexts, { id: updatedText.id });
  myObjectToUpdate = updatedText;

console.log (myObjectToUpdate);
console.log (arrTexts);
};
Run Code Online (Sandbox Code Playgroud)

“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);
};
Run Code Online (Sandbox Code Playgroud)

非常感谢您的帮助!

Shu*_*tri 6

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);
};
Run Code Online (Sandbox Code Playgroud)

你也可以像这样更新它

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);
};
Run Code Online (Sandbox Code Playgroud)