Pass state from child to parent component in React Native

My application has a settings screen (a child component) in which you can change information about yourself, and I'm trying to get this to display the application profile on the screen (parent component). Thus, the profile screen displays your information and if you want to change any information that you do in the settings. Right now, any changes I make on the settings screen are displayed in Firebase, but if I go back to the profile screen, the changes in the settings will not be displayed. Of course, if I close the application and restart it, the changes will be there, because the changes in the settings are registered on firebase; however, the state does not pass from the child component to the parent component. Does anyone have any tips on how to pass state from the settings component (child) to the profile component (parent)?

+5
source share
3 answers

You can try reducex, it stores data in state through props when you change data in redux store.

Another idea: pass the setState method to the child component.

Parent

class Parent extends Component { updateState (data) { this.setState(data); } render() { <View> <Child updateParentState={this.updateState.bind(this)} /> </View> } } 

Child

 class Child extends Component { updateParentState(data) { this.props.updateParentState(data); } render() { <View> <Button title="Change" onPress={() => {this.updateParentState({name: 'test'})}} /> </View> } } 
+4
source

You should look into a state management module such as Redux to see if it will work with your application, but without this, you can achieve this by doing something like this:

 // --------------------------------------------- // Parent: class Parent extends React.Component { updateData = (data) => { console.log(`This data isn't parent data. It ${data}.`) // data should be 'child data' when the // Test button in the child component is clicked } render() { return ( <Child updateData={val => this.updateData(val)} /> ); } } // --------------------------------------------- // Child: class Child extends React.Component { const passedData = 'child data' handleClick = () => { this.props.updateData(passedData); } render() { return ( <button onClick={this.handleClick()}>Test</button> ); } } 
+1
source

After trying several different options, we decided to implement Redux to control the state in our application. It was hard to do with our navigation, but now that everything is set up, I would say that it is worth it. There are other solutions for managing state systems, such as MobX, to which we contributed, but decided to go with Redux, because it matches our navigation layout.

+1
source

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


All Articles