Accessing props in React constructor

Viewed 1981

I have a problem when I try to access parent's props value in the child class.

I am trying to initialize the child props with the parent's props.

But the following code shows me empty string of value.

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

In other class I call this Child as follows:

const issue = this.state.issue;
...
<Child value={issue.number} />
...

I checked the number value before Child class is constructed (it shows me correct values), while it is construced, the value becomes empty..

For test, I used primitive number value, and it works.

Seems like some kind of link to issue.number is disconnected when Child is contructed.

Any clue?

2 Answers

This could easily happen. For example, issue.number becomes a number after AJAX re-rendering. In this case you have to do follow (in your parent component):

render() {
  const issue = this.state.issue


  if (issue.number) {
    return <Child value={issue.number} />
  }
}

Ah, I just figured it out.

It is related to Lifecycle.

The number value is not loaded when I render Child.

So, I need to figure it out how to update the number in Child with my intention.

Related