更新没有变异的对象数组

Zea*_*ith 5 javascript babel ecmascript-6 reactjs

我正在关注反应教程,但我迷路了.我不明白第9行.

在此输入图像描述

所以我试着做一点温度

const updateTodo = (list, updated) => {
   const index = list.findIndex(item => item.id === updated.id)
   return [
   ...list.slice(0,index),
   updated,
   ...list.slice(index+1)
   ]
}
Run Code Online (Sandbox Code Playgroud)

https://jsbin.com/sifihocija/2/edit?js,console但未能产生作者所做的结果,出了什么问题?

May*_*kla 8

问题在这一行:

const index = list.findIndex(item => item.id === updated.id)

更新是一个array,访问ID,你需要指定index另外,对于其他的array你正在使用loop,因此item将是各objectarray,并且item.id会给你的id每一个object,试试这个:

const index = list.findIndex(item => item.id === updated[0].id)

const arr = [
  {id:1,name:'hello'},
  {id:2,name:'hai'}
]

const arr2 = [
  {id:2,name:'this should be a new string'}
]

const updateTodo = (list, updated) => {
   const index = list.findIndex(item => item.id === updated[0].id);
   return [
   ...list.slice(0,index),
   ...updated,
   ...list.slice(index+1)
   ]
}

console.log(JSON.stringify(updateTodo(arr,arr2)))
Run Code Online (Sandbox Code Playgroud)

检查工作代码:https : //jsbin.com/pazakujava/edit?js,console

如果您在这方面需要任何帮助,请告诉我。