简体   繁体   中英

How to disconnect child props from Parent's state passed in?

I have seen a lot of questions regarding updating a parent's state from a child component, however my question is just the opposite. I have a component, a modal editing window, used for modifying objects stored in a parent's state. I only want to have these changes copied to the parent if the user saves these changes, which is handled by a function I pass to the child component. Currently, anytime I make a change to the prop.obj in the child, the change is picked up by the parent on re-render.

here is an example of one of my change handlers

handleChange(e) {
    this.state.childobj.myvaluetochange = e.target.value
}

In my parent, as stated, I pass obj to the child from the parent's state like so

<MyComponent obj={this.state.obj} />

to summarize:

I send a state object to a child

The child uses this.props.obj to use this obj in a form and uses handlers to update

When changes are picked up in the child, they reflect on the parent's state object on update - I don't want this unless they choose to save. (this is handled by a function passed in from the parent)

to clarify, I want the state obj passed to the child to act as a completely separate object when it lives in the child. Is this possible?

Thanks

This is happening because you are mutating the given prop.

To avoid this you should create new instance of "this.props.obj". Probably you want to do it in "componentWillMount" and "componentWillReceiveProps" lifecycle methods. To create new instance of object you can use Object.assign or spread operators.

You are creating a link to the parent object and then mutating the state which will reflect in the parent. An easy way around this is to create a new version of it by using the spread operator to create a new object:

this.state = {childObj: {...this.props.obj}}

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