简体   繁体   中英

Weird destructuring behavior in React

I have a deeply nested JSON object as state initially made with useState hook -


 const [template, setTemplate] = useState([
    {
      
      statement: 'this is top level statement',
      nestingLevel: 0,
      children: [
        {
          nestingLevel: 1,
          statement:
            'this is a statement with such a template',
          children: [
            { 
              statement: 'first chart',
              nestingLevel: 2,
            },
            { statement: 'second chart',
              nestingLevel: 2,
            },
          ],
        },
      ],
    },
    {
     
      statement:
        'this is second statement for section with such a metric {{}}',
      nestingLevel: 0,
      
    },
  ]);

I have an input element with an onChange handler.

As you can see, whenever there is some change in the input text, I update some relevant key-value pair based on path. I do so by using the lodash library's get and set functions.


 const handleDataChange = (e, path) => {
        console.log('handling the data');
        // copy the template
        let templateCopy = template;
        // create the new object with updated information
        const tempObj = _.set(
          templateCopy,
          `${path}['statement']`,
          e.target.value,
        );

        setTemplate([...tempObj]);
      };

The problem is in the handleDataChange function. When I do setTemplate(tempObj) the state doesn't get updated. However when I do setTemplate([...tempObj]) (which will essentially yield the same result), this later solution works as expected.

I want to know why that is the case. Is it because lodash gives results always as object and destructuring and repacking it make it array again and hence it works as expected?

The object reference stays the same when you mutate nested property only, and as react does shallow comparison in order to detect changes, it won't react to the change.

You can deepClone the object, then mutate it as you do with set and then update the state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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