Right way to clone objects / arrays during setState in React

前端 未结 4 1353
温柔的废话
温柔的废话 2021-02-20 10:36

I start with:

constructor() {
   super();
      this.state = {
         lists: [\'Dogs\',\'Cats\'], 
         items: {Dogs: [{name: \"Snoopy\"}, {name: \"Lola\"         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-20 11:08

    The chosen answer was a miracle and huge props to Nandu Kalidindi, I was having bugs with nested arrays inside of objects that I was updating in my project and was not understanding the concept of "deep" or "nested" arrays and objects not being copied to a new object.

    This is my take on his fix and made it look a little more appealing to me and works just as good!

    I utilize lodash and found their _.cloneDeep() function to serve my updating state needs.

    Lodash _.cloneDeep()

    I learned that mapping out updated arrays preventing any bugs was the best way to treat that kind of problem, but I was cloning entire objects with nested arrays that were mutating the old object's arrays in the state.

    This is my answer.

    
    const state = {
        fields: {
            "caNyDcSDVb": {
                id: "caNyDcSDVb",
                name: "test1",
                type: "text",
                options: ["A", "B", "C"]
            }
        },
    };
    
    const FieldCopy = (id) => {
        const newCopiedField = _.cloneDeep(state.fields[id]);
        newCopiedField.id = nanoid(10);
        return {
            ...state,
            fields: {
                ...state.fields,
                newCopiedField[id]: newCopiedField
            }
        };
    };
    

提交回复
热议问题