javascript - Changing a child components state changes the parent components props -


parent component header

child component form used change values appearing in header after save fires redux action.

i set child state with

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

the form used render state.object , modify state.object. when modify state.object, props parent component change well.

handleobjectchange = (event, key, subkey) => {     console.log('props', this.props.object.params);     console.log('state', this.state.object.params);     event.preventdefault();     const value = this.handleperiod(event.target.value);     this.setstate((prevstate) => {       const object = { ...prevstate.object };       object[key][subkey] = value;       return { object };     }); } 

console output:

newvalueijusttyped newvalueijusttyped 

this behavior goes way modifying redux store without ever having dispatched action.

would appreciate solution issue

update:

changing constructor solved issue

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

why doesn't object spread operator achieve i'm trying accomplish?

javascript object assigned reference when do

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

state referencing redux state object(if redux state). when use

this.setstate((prevstate) => {   const object = { ...prevstate.object };   object[key][subkey] = value;   return { object }; }); 

although assume have cloned object value new object. spread syntax 1 level copy of object.

from spread syntax mdn docs:

note: spread syntax goes 1 level deep while copying array. therefore, may unsuitable copying multidimensional arrays following example shows (it's same object.assign() , spread syntax).

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

so

object[key][subkey] = value; 

changes value directly in redux store.

solution create nested copy like

  const object = { ...prevstate.object,                       [key]: {                           ...prevstate[key],                           [subkey]: { ...prevstate[key][subkey]}                       }                    };   object[key][subkey] = value; 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -