简体   繁体   English

redux 复制数组后反应更新数组

[英]redux react update array after copying array

I have a question I'm facing a problem that I can't update array after copying it.我有一个问题,我遇到了复制后无法更新数组的问题。 If I copy an array and don't update the id, when I type something on input the text will appear in the same way where I copy it.如果我复制一个数组但不更新 id,当我在输入中键入内容时,文本将以与复制它相同的方式出现。

here is my Initialstate这是我的初始状态

const initialState = [
  {
    id: random numbers,
    options: [{ id: random numbers , value: '' },
    ],
  },
];

it will have a lot of option and I just would like to update options id它会有很多选项,我只想更新选项 ID

this is what i tried这是我试过的

    case COPY_QUESTION: {
      const newArray = [...state];
      const copyQuestion = newArray[action.payload];
        copyQuestion.options.map((option) =>
          Object.assign({}, option, {
            id: random number,
          }),
        );
      
      return [...state, copyQuestion];
    }

thanks for reading my question.感谢阅读我的问题。

it's caused due to call-by-reference.这是由于引用调用引起的。 As I can see in your code, You are copying the reference of an array which might have the reason to overwrite details of the original array when you are typing.正如我在您的代码中看到的那样,您正在复制一个数组的引用,这可能有理由在您键入时覆盖原始数组的详细信息。 You can copy the values of the original array by using Javascript Object Prototype您可以使用 Javascript Object 原型复制原始数组的值

so in that, you need to destruct your array or break your reference in the duplicate array.因此,您需要破坏数组或破坏重复数组中的引用。 example例子

let A = [a,b,c]  //original Array
let B =  JSON.parse(JSON.strigify(A))  // duplicate Array

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

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