Local React prop read-only

Say I have two Components. The parent receives the object as a property, which then copies to the local data store. It has the function of updating this local storage, which is passed to the child. Here is my parent component:

const Parent = ({stuff}) => {
  const store = {
    stuff: Object.assign({}, stuff);
  }

  const updateStuff = (thing, property) => store.stuff[thing].property = thing;

  return <Child stuff={stuff} updateStuff={updateStuff} />
}

The child component has a similar structure - it creates a copy stuffand mutates its copy stuffon <input> onChange. He then passes his own updated copy of the material to his function updateStuffto change the parent copy of the prop. Here is the baby.

const Child = ({stuff, updateStuff}) => {
  const stuff = {
    thing1: Object.assign({}, stuff.thing1),
    thing2: Object.assign({}, stuff.thing2)
  }

  const setProp = event => {
    const update = event.target.value;

    stuff.thing1.prop = update;
    updateStuff(thing1, stuff.thing1.prop)
  }

  return (
    <div>
      <input id="thing1" onChange={setProp} />
      <input id="thing1" onChange={setProp} />
    </div>
  )
}

: Object.assign, stuff prop , . : React prop - , , , ( )/

Child - setProp stuff, . , updateTeam, : Uncaught TypeError: Cannot assign to read only property 'side' of object '#<Object>'

, : , . Child, Parent?

+4
2

Object.assign prop Object.assign Reference. ( ), newStuff: JSON.parse(JSON.stringify(stuff)). , !

:

let original = {
    name: 'Test',
    nestedObj: {
        (...some properties)
    }
}

"" , . , , , .

+4

const let .

-3

Source: https://habr.com/ru/post/1666449/


All Articles