Skip to content Skip to sidebar Skip to footer

Changing A Child Components State Changes The Parent Components Props

Parent component is a header Child component is a form which is used to change values appearing in the header after a save which fires a redux action. I set the child state with co

Solution 1:

Javascript object are assigned by reference so when you do

constructor(props) {
    super(props);
    this.state = {
      object: props.object,
      hidden: props.hidden,
    };
}

state is referencing the redux state object(if it is a redux state). So now when you use

this.setState((prevState) => {
  constobject = { ...prevState.object };
  object[key][subkey] = value;
  return { object };
});

Although you would assume that you have cloned the object value into a new object. However Spread syntax does only a one level copy of the object.

From the Spread Syntax MDN docs:

Note: Spread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multidimensional arrays as the following example shows (it's the same with Object.assign() and spread syntax).

var a = [1, [2], [3]]; var b = [...a]; b.shift().shift(); // 1 // Now array a is affected as well: [[], [2], [3]]

So effectively

object[key][subkey] = value;

changes the value directly in redux store.

Solution is create a nested copy like

constobject = { ...prevState.object,
                      [key]: {
                          ...prevState[key],
                          [subkey]: { ...prevState[key][subkey]}
                      }
                   };
  object[key][subkey] = value;

Solution 2:

Objects in javascript are 'passed by reference'.

If you are passing the parent's props as state to the children, then when you change the state, you are in effect mutating the very same object that was passed to it.

Use Object.assign() to create a clone of the data before you make it part of the child's state.

Post a Comment for "Changing A Child Components State Changes The Parent Components Props"