简体   繁体   English

使用价差语法ES6

[英]Working with Spread Syntax ES6

I am using spread syntax to replace an object in an array but I can't the object is added as a new entry of my array. 我正在使用扩展语法替换数组中的对象,但无法将对象添加为数组的新条目。

state = {8xf0y6ziyjabvozdd253nd:[
  {
    "id": "894tuq4ut84ut8v4t8wun89g",
    "parentId": "8xf0y6ziyjabvozdd253nd",
    "timestamp": 1503045227866,
    "body": "Hi there! I ams a COMMENTSsg.",
    "author": "thingtwo",
    "voteScore": 143,
    "deleted": false,
    "parentDeleted": false
  },
]}

First I find the index of the element that I want to replace with this function: 首先,我找到要用此函数替换的元素的索引:

let index = state[payload.id].findIndex((element)=> element.id === payload.data.id)

And then I use the spread syntax to create a new state and replace the element inside of the array: 然后,我使用传播语法创建一个新状态并替换数组中的元素:

return { ...state,
                [payload.id]:[...state[payload.id],index=payload.data]
            }

But it returns this: 但它返回以下内容:

    {8xf0y6ziyjabvozdd253nd:[
          {
            "id": "894tuq4ut84ut8v4t8wun89g",
            "parentId": "8xf0y6ziyjabvozdd253nd",
            "timestamp": 1503045227866,
            "body": "Hi there! I am a COMMENTS.",
            "author": "thingtwo",
            "voteScore": 143,
            "deleted": false,
            "parentDeleted": false
          },
          {
            "id": "894tuq4ut84ut8v4t8wun89g",
            "parentId": "8xf0y6ziyjabvozdd253nd",
            "timestamp": 1503045227866,
            "body": "Hi there! I am a COMMENTS Replace",
            "author": "thingtwo",
            "voteScore": 143,
            "deleted": false,
            "parentDeleted": false
          }
        ]}

The expected output: 预期输出:

{8xf0y6ziyjabvozdd253nd:[
              {
                "id": "894tuq4ut84ut8v4t8wun89g",
                "parentId": "8xf0y6ziyjabvozdd253nd",
                "timestamp": 1503045227866,
                "body": "Hi there! I am a COMMENTS Replace",
                "author": "thingtwo",
                "voteScore": 143,
                "deleted": false,
                "parentDeleted": false
              }
            ]}

You might use Object.assign for updating properties of the found object (with Array#find ). 您可以使用Object.assign来更新找到的对象的属性(使用Array#find )。

let object = state[payload.id].find((element)=> element.id === payload.data.id);

Object.assign(object, payload.data);

Spread syntax/operator is used to spread an object into comma separated keys. 传播语法/运算符用于将对象传播为逗号分隔的键。

In your state, every key is payload id and you want replace one entry in that payloads value, which is an array. 在您的状态下,每个键都是有效负载ID,并且您想要替换该有效负载值中的一个条目,该值是一个数组。 So you need to go to that payload by id, go to the index in that payloads value array and replace that value with new value. 因此,您需要按id转到该有效负载,转到该有效负载值数组中的索引,然后用新值替换该值。 below code should give you the expected output, 下面的代码应该给您预期的输出,

let index = state[payload.id].findIndex((element)=> element.id === payload.data.id);
state[payload.id][index] = payload.data;
console.log(state);

You should use spread syntax when you want to replace the complete array for that payload, and here you want to replace an entry in that array and not complete array. 当您要替换该有效负载的完整数组时,应该使用扩展语法,并且在此处您想要替换该数组中的条目而不是完整数组。

Edit for avoiding mutation 编辑以避免突变

1. Using Object.assign will mutate state, 1.使用Object.assign会改变状态,

let index = state[payload.id].findIndex((element)=> element.id === payload.data.id);
let stateCopy = Object.assign({}, state);
stateCopy[payload.id][index] = payload.data;
console.log(state);
console.log(stateCopy);

Check both state & stateCopy gets modified 检查state和stateCopy是否被修改

2. Using spread syntax will mutate state, 2.使用传播语法会改变状态,

let index = state[payload.id].findIndex((element)=> element.id === payload.data.id);
let stateCopy = {...state}
stateCopy[payload.id][index] = payload.data;
console.log(state);
console.log(stateCopy);

Check both state & staeteCopy gets modified 检查状态和staeteCopy是否被修改

3. Use cloning to avoid mutation of original state, 3.使用克隆避免原始状态的突变,

install esclone, 安装esclone,

 #> npm install --savedev esclone

go to your file and add import, 转到您的文件并添加导入,

 import esclone from "esclone";

And use below code to achieve the expected output without mutation, 并使用以下代码实现预期的输出而不会发生变化,

let index = state[payload.id].findIndex((element)=> element.id === payload.data.id);
let stateCopy = esclone(state);
stateCopy[payload.id][index] = payload.data;
console.log(state);
console.log(stateCopy);

Check original state is not modified 检查原始状态未修改

Note: Object.assign & spread syntax performs only a reference copy and not deep copy, hence you need to use some deep clone mechanism like esclone library. 注意: Object.assign和spread语法仅执行参考副本,而不执行深层副本,因此您需要使用某些深层克隆机制,例如esclone库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM