Pass state from child to parent component in React Native

爱⌒轻易说出口 提交于 2019-12-06 23:58:32

问题


My app has a settings screen (child component) where you can change information about yourself and I'm trying to get that to render on my app's profile screen (parent component). So the profile screen displays your info and if you want to change any info you do it in settings. Right now any changes I make in the settings screen show up in Firebase but if I go back to the profile screen the changes in settings don't render. Of course if I close the app and reload it the changes will be there because the changes in settings are registering to firebase; however, the state is not passing up from the child component to the parent. Does anyone have any advice on how to pass state from the settings (child) component up to the profile (parent) component?


回答1:


You can try redux, It store data in state by props whenever you change data in redux store.

Other idea is, pass a setState method to 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>
    }
}



回答2:


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

// ---------------------------------------------
// Parent:

class Parent extends React.Component {
  updateData = (data) => {
    console.log(`This data isn't parent data. It's ${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>
    );
  }
}



回答3:


After trying several different options, we decided to implement Redux to manage state in our app. This was difficult to do with our navigation, but now that everything is set up I'd say it was well worth the effort. There are other state management solutions like MobX we looked into, but decided to go with Redux because it fit with our navigation layout.



来源:https://stackoverflow.com/questions/44875787/pass-state-from-child-to-parent-component-in-react-native

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