繁体   English   中英

React Child 道具变量未定义,即使我之前定义了变量

[英]React Child prop variable is undefined even though I defined the variable before

所以我想显示一个人员列表。在我的父组件中,我map是一个person array 每个人都有姓名、名字和年龄。 显示具有所有属性的每个人都没有问题,但我在“r”上有一个键绑定,如果我稍后在键盘上按“r”,我想控制台记录一个特定人的年龄。 所以这就是为什么我在 Person 组件中定义了一个按键 function。 但是现在,如果我在键盘上按“r”,我会收到以下错误:“ TypeError: Cannot read property 'person' of undefined ”在我试图控制台记录该人的年龄的行中。

这基本上是我的父类( PersonList.js ):

{ personList.map((person, index) => {       //mapping a person list (e.g. 5 persons with 
                                            //name,firstname and age for each enty

          let active= this.state.activePerson    //true if person is active, else: false
           return (
                    <Person person={person} index={index} active={active}/>
                  )

})}

这是我的子组件 ( Person.js ):

export default class Person extends Component {

constructor(props) {
    super(props);
    this.state = {
        active: false,
        person: this.props.person,
    };
}
componentWillReceiveProps(nextProps) {
    this.setState({ active: nextProps.active });
}

componentWillMount() {
    document.addEventListener("keydown", this.onKeyPressed, false);
}

componentWillUnmount() {
    document.removeEventListener("keydown", this.onKeyPressed, false);
}

onKeyPressed(e) {
    const keyCode = e.keyCode

    if (keyCode === 82) {  //if I press r on the keyboard, the name of the active person should be 
                           //displayed (I set the attribute active to true if I click on the person 
                           //card)

        console.log("the person "+ this.state.person.name+ "is" + this.state.person.age)
    }
}

render() {
    return (

           <Card className={this.state.active}>
                {this.state.person.name}
                {this.state.person.firstname}
                {this.state.person.name}
           </Card>

所以每张卡片都能正确显示,但如果我按“r”,我会得到 T ypeError: Cannot read property 'person' of undefined 我在 stackoverflow 上找不到关于这个问题的任何信息。 希望任何人都可以帮助我。

干杯:-)

你的构造函数应该是这样的

constructor(props) {
  super(props);
  this.state = {
    active: false,
    person: props.person,
  };
}

您没有绑定您的 function。使用箭头 function 或添加this.onKeyPressed = this.onKeyPressed.bind(this); 给你的构造函数。

“This”在您的“onKeyPressed”处理程序中不可用 function

绑定事件或使用箭头 function

document.addEventListener("keydown", this.onKeyPressed.bind(this), false);

要么

onKeyPressed = e => {
const keyCode = e.keyCode;

if (keyCode === 82) {
  //if I press r on the keyboard, the name of the active person should be
  //displayed (I set the attribute active to true if I click on the person
  //card)

  console.log(
    "the person " + this.state.person.name + "is" + this.state.person.age
  );
}

};

暂无
暂无

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

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