Dealing with Nested React Components' State Changes

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-01 09:04:26

cough, redux, cough

Anyway, passing props is a one way street! You can pass things down, and use them, but you can't pass them up. The only way to manipulate a parent component is through passing an entire function as props.

updateGrandpaState(newData){
this.setState({ originalData: newData})
}

From your grandpa component you you would pass it down like this...

<ParentComponent updateGrandpaState={this.updateGrandpaState} />

And inside your parent component you can call

this.props.updateGrandpaState(parentComponentData)

Which will then fire the original function that lives in grandpaComponent, thus updating grandpaComponent State.

And yes, you can go further, forewarning, the deeper you go the uglier it gets...

Inside Grandpa

< ParentComponent updateGrandpaState={this.updateGrandpaState} /> 

Inside Parent

< ChildComponent updateGrandpaState={this.props.updateGrandpaState} />

Inside Child

this.props.updateGrandpaState(childComponentData)

When you go two levels deep I also console.log(this.props) on componentDidMount while doing dev work.

To make things even cooler, you could even pass grandpaState down into ParentComponent to use, which you could hook up to componentWillRecieveProps.....

<ParentComponent grandpaState={this.state} updateGrandpaState={this.updateGrandpaState} />

But honestly, once you learn redux, set it up a few times, it's really awesome and I would never not use it!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!