zzq zzq - 16 days ago 8
React JSX Question

How to change the data in react, i copy to the props to state




How to change the data



I have read a book, the author said do not copy to the props to state, so if i want want to change the data, which is the right way.

https://i.stack.imgur.com/EPUFq.png

Answer

Well when you go through the docs it states that, setting props to the initial state is an anti pattern. So instead of initially setting your prop to state, you can do that in the componentDidMount() lifecycle function

constructor(props) {
   super(props);
   this.state = {
      birthdate: null,
      name: null,
      contact: null,
      gender: null,
      photoUrl: 'https://facebook.github.io/react/img/logo_og.png'
   }
}
componentDidMount() {
    const {birthdate, name, contact, gender, photoUrl} = this.props;
    this.setState({
        birthdate: birthdate,
        name: name,
        gender: gender,
        contact: contact,
        photoUrl: photoUrl
    })
}