Javascript React Child prop变量未定义,即使我以前定义过该变量

Javascript React Child prop变量未定义,即使我以前定义过该变量,javascript,reactjs,react-props,Javascript,Reactjs,React Props,因此,我想显示一个人员列表。在我的父组件中,我将映射一个数组中的人员。每个人都有名字、名字和年龄。 显示所有属性的每个人都没有问题,但我在“r”上有一个键绑定,如果我以后按键盘上的“r”,我想控制台记录一个特定人的年龄。这就是为什么我在Person组件中定义了一个按键功能。但现在如果我按键盘上的“r”,我会得到以下错误:“TypeError:无法读取未定义的属性“person””,在我试图用年龄记录该人的行中 这基本上是我的父类(PersonList.js): 因此每张卡都能正确显示,但如果我按

因此,我想显示一个人员列表。在我的父组件中,我将
映射
一个
数组
中的
人员
。每个人都有名字、名字和年龄。 显示所有属性的每个人都没有问题,但我在“r”上有一个键绑定,如果我以后按键盘上的“r”,我想控制台记录一个特定人的年龄。这就是为什么我在Person组件中定义了一个按键功能。但现在如果我按键盘上的“r”,我会得到以下错误:“
TypeError:无法读取未定义的属性“person”
”,在我试图用年龄记录该人的行中

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

因此每张卡都能正确显示,但如果我按“r”,我会得到T
ypeError:无法读取未定义的属性“person”。我在stackoverflow上找不到有关此问题的任何信息。希望任何人都能帮助我


干杯:-)

您的构造函数应该如下所示

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

你没有绑定你的函数。使用箭头功能或添加
this.onKeyPressed=this.onKeyPressed.bind(this)到构造函数。

在“onKeyPressed”处理程序函数中“This”不可用

绑定事件或使用箭头函数

document.addEventListener(“keydown”,this.onKeyPressed.bind(this),false)


})

为什么您的Person组件有任何状态?直接记录道具谢谢,它起作用了:-)过去几天我一直在努力解决这个问题:D
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>
constructor(props) {
  super(props);
  this.state = {
    active: false,
    person: props.person,
  };
}
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
  );
}