[英]update array of object without mutation
I'm following a react tutorial but I'm lost.我正在学习反应教程,但我迷路了。 I don't understand starting line 9.
我不明白起始行 9。
so I tried to make a little miarature所以我试着做一个小小的幻觉
const updateTodo = (list, updated) => {
const index = list.findIndex(item => item.id === updated.id)
return [
...list.slice(0,index),
updated,
...list.slice(index+1)
]
}
https://jsbin.com/sifihocija/2/edit?js,console but failed to produce the result that the author did, what's wrong? https://jsbin.com/sifihocija/2/edit?js,console却没有产生作者做的结果,怎么回事?
Issue is in this line: 问题在于这一行:
const index = list.findIndex(item => item.id === updated.id)
updated is an array
, to access the id, you need to specify the index
also, for other array
you are using loop
, so item
will be the each object
of the array
, and item.id
will give you the id
of each object
, try this: updated是一个
array
,要访问id,你还要指定index
,对于你正在使用loop
其他array
,所以item
将是array
的每个object
,而item.id
将给你每个object
的id
,尝试这个:
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)))
Check the working code: https://jsbin.com/pazakujava/edit?js,console 检查工作代码: https : //jsbin.com/pazakujava/edit?js,console
Let me know if you need any help in this. 如果您需要任何帮助,请告诉我。
Change the 改变
...list.slice(index+1)
to 至
...list.slice(index,0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.