简体   繁体   中英

Accessing props in React constructor

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?

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.

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