简体   繁体   中英

How To Update State In Parent Component From Child Component In React Native?

Current Code

Parent.js

export default class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      nickname: 'parent'
    };
  }
}

Child.js

export default class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      nickname: props.navigation.state.params.nickname
    };
  }

  onPressUpdate() {
    const { nickname } = 'Child';
      this.props.navigation.navigate('Parent', { nickname: nickname });
  }
}

What I'm Trying To Do

Parent.js displays nickname and it is edited in Child.js. Finishing to edit nickname, navigation goes back to Parent.js. Then I wanna display a new nickname, 'Child' in above code. I would appreciate it if you could give me any advices:)

You could use componentDidUpdate in parent code.

Something like this:

componentDidUpdate(prevProps) {
  // Typical usage (don't forget to compare props):
  if (this.props.nickname !== prevProps.nickname ) {
    this.seteState({nickname:this.props.nickname});
  }
}

When you navigate from child to parent, pass the nickname to update, it will work and setState to new one.

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