Cannot setState from props in React from parent to child

702 Views Asked by At

I am trying to pass -from parent to child component- some data as props and I would like to set this prop to initial state.

class EditContact extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: this.props.name,
      phone_number: this.props.phone_number,
      address: this.props.address
    };
    this.handleInputChange = this.handleInputChange.bind(this);
  }
  ...
}

I am not getting any errors, but if I console.log this.state.name I get nothing. or when I check it in chrome-s react add-on I can see the props values, but state remains "".

I have also tried to sort it with getDerivedStateFromProps in componentDidMount, I can set it with that but then it doesn`t let me change the state later on...Why?! What can be wrong?

2

There are 2 best solutions below

2
On

Make sure the value of props is the expected when you assign them to the state.

super(props);
debugger; // This will act as a break point in chrome

Most likely the issue is that the value of props is empty by the time they are assigned to the state.

0
On

Use

props.name

instead of

this.props.name