![](/img/trans.png)
[英]Variable appears as undefined in loop even though it is defined before the loop
[英]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.