【问题标题】:update array of object without mutation更新没有突变的对象数组
【发布时间】:2017-02-05 14:25:34
【问题描述】:

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

所以我试着做一个小人物

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却没有产生作者所做的结果,这是怎么回事?

【问题讨论】:

    标签: javascript reactjs ecmascript-6 babeljs


    【解决方案1】:

    问题出在这一行:

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

    updated 是 array,要访问 id,您还需要指定 index, 对于其他array,您正在使用loop,因此item 将是array 的每个object,而item.id 将为您提供每个objectid,试试这个:

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

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

    如果您需要任何帮助,请告诉我。

    【讨论】:

    • 你能解释一下为什么作者不需要这样做吗?我的意思是更新[0].id
    • 教程在这里egghead.io/lessons/…
    • 因为在他的情况下,arr2 将是一个对象,像这样:const arr2 = {id:2,name:'this should be a new string'} 你可以试试这个 arr2,你的代码也可以工作:)
    • 啊 arr2 应该是一个对象,它不应该是一个数组,我认为这是我的错误,如果 arr2 是一个数组,那就没有意义了。
    猜你喜欢
    • 2017-07-28
    • 2020-06-01
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 2019-03-23
    • 2019-01-01
    • 2021-04-20
    • 1970-01-01
    相关资源
    最近更新 更多