Итак, я хочу отобразить список людей. В моем родительском компоненте я map
и array
из person
. У каждого человека есть имя, имя и возраст. Нет проблем с отображением каждого человека со всеми атрибутами, но у меня есть клавиша на «r», и если я позже нажму «r» на своей клавиатуре, я хочу, чтобы консоль регистрировала возраст одного указанного c человека. Вот почему я определил функцию нажатия клавиш в компоненте Person. Но теперь, если я нажимаю «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
. Я не мог найти ничего об этой проблеме на стеке потока. Надеюсь, кто-нибудь может мне помочь.
Приветствия: -)