简体   繁体   English

在 React 构造函数中访问 props

[英]Accessing props in React constructor

I have a problem when I try to access parent's props value in the child class.当我尝试在子类中访问父类的 props 值时遇到问题。

I am trying to initialize the child props with the parent's props.我试图用父母的道具初始化子道具。

But the following code shows me empty string of value .但是下面的代码向我展示了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..我在构造 Child 类之前检查了数值(它显示了正确的值),而在构造它时,该值变为空..

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.似乎某种指向 issue.number 的链接在 Child 被构造时断开连接。

Any clue?有什么线索吗?

This could easily happen.这很容易发生。 For example, issue.number becomes a number after AJAX re-rendering.例如, issue.number成为 AJAX 重新渲染后的数字。 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.渲染 Child 时未加载数值。

So, I need to figure it out how to update the number in Child with my intention.所以,我需要弄清楚如何按照我的意图更新 Child 中的数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM