简体   繁体   中英

Update in one setState property causes another property change automatically in reactjs

I have one table in parent component and form fields in child component. I am passing onchange function as props to receive values changed on the child component in parent and assigning the value to state property. But while change in the particular setState property causes change in another setState property automatically. Attached sample code for reference.

 import React, { Component } from 'react';
    import _ from 'lodash';

    state = {
            activeLanguage: localStorage.selectedLanguage,
            obj1: {},
            obj2: []
        };

        componentDidMount = () => {
            this.setState({
                obj1: this.fetchUserDetails()[0],
                obj2: this.fetchUserDetails()

            });
        }

        fetchUserDetails = () => {
            const tempUserTable = [];
            const userInfo = {
                primaryAddress: {
                    addressLine1: 'Test',
                    addressLine2: 'Test',
                    city: 'Test'
                }
            };
            tempUserTable.push(userInfo);
            return tempUserTable;
        }

    handleChange = (value, path) => {
        const { obj1, obj2 } = this.state;
        console.log('Before set method:: ' + obj2);
        //obj1 primaryAddress.addressLine1 value changed from 'Test' to 'Testchange' after next line invoked
        _.set(obj1, path, value); 
        //obj2 primaryAddress.addressLine1 value changed from 'Test' to 'Testchange' automatically
        console.log('After set method:: ' + obj2); 
        this.setState({
            obj1
        });
    };

For example, I am receiving value, path from child component in onChange function to update the obj1 using setState. It causes change in obj2 automatically.

Example value change happened at runtime.

addressLine1 of obj1 field value changes from 'Test' to 'Testchange' - (value='Testchange', path='primaryAddress.addressLine1') - onChange called in parent and setState of obj1 invoked. addressLine1 of obj2 field value changes from 'Test' to 'Testchange' - This is happened automatically without calling setState for this obj2.

Any help would be greatly appreciated. Please let me know if any info required further.

I'm not sure how you're doing your data fetching outside of this sample code, but my guess is this is happening because of the way you're setting obj1 and obj2 . obj1 and obj2[0] may actually be pointing to the same space in memory. Unlike primitives like numbers and strings, objects and arrays are treated like pointers in JS.

To get around this, we'll need to clone obj2[0] into its own value. Since you're already using Lodash, one option is using their clonedeep method. Something like this may solve your problem:

componentDidMount = () => {
  const data = this.fetchUserDetails();
  this.setState({
    obj1: _.clonedeep(data[0]),
    obj2: data
  });
}

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