【问题标题】:How can i properly clone json array in redux?如何在 redux 中正确克隆 json 数组?
【发布时间】:2017-01-27 17:24:46
【问题描述】:

我是 Redux 的新手,起初我觉得 Redux 概念很奇怪。假设我有一个处于 redux 状态的数组。

const state = [ 
  {show: false, id : '1'},
  {show: false, id : '2'},
  {show: false, id : '3'},
  {show: false, id : '4'},
  {show: false, id : '5'}
]

我想克隆这个数组并改变/改变一个对象。

我在 reducer 中尝试过类似的操作,但没有成功。

   return  [...state.concat(Object.assign({}, state[0], {show:true} )).slice(1,5)];

任何帮助或解释都会很好。

【问题讨论】:

    标签: javascript arrays reactjs redux


    【解决方案1】:

    我认为您可能在问题中将[] 切换为{}

    假设你的状态是:

    const state = [ 
      { show: false, id: '1' },
      { show: false, id: '2' },
      { show: false, id: '3' },
      { show: false, id: '4' },
      { show: false, id: '5' }
    ]
    

    你可以这样写一个reducer:

    return [
      ...state.slice(0, index),
      Object.assign({}, state[index], { /* your changes */ })
      ...state.slice(index + 1)
    ]
    

    其中index 是您要更改的元素的索引。

    参考文献

    【讨论】:

    • 我想改变数组中的第一个对象,我试过这个:return [...Object.assign({}, state[0], {show:true} ), ...slice( 1,5)] 它只返回最后 4 个对象,第一个丢失了...
    • 在你的情况下应该是...state.slice
    • 还是一样,它只返回 4 个元素,首先我要变异的元素不在返回的数组中... :(
    • 不要在接头中指定长度。看我的例子,只要用...state.slice(1)就可以得到剩余的数组项。
    • 它现在可以工作了,我在 Object.assign 之前删除了扩展运算符,看起来没有必要。返回 [Object.assign({}, state[0], {show:true} ), ...state.slice(1)]
    猜你喜欢
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    相关资源
    最近更新 更多