【发布时间】:2021-11-24 13:56:52
【问题描述】:
这是一个 Reactjs 代码。在这里,我正在尝试迭代和打印对象数据。但是,面临一个错误——> TypeError: Cannot read properties of undefined (reading 'state')。我想知道我在这里做错了什么。
import React, { Component } from 'react'
class App extends Component {
state = {
posts: {
ASlot: true,
BSlot: true,
CLive: true,
DRedirect: true
}
}
Club() {
for(const property in this.state.posts) {
console.log('hello')
// console.log(`${property}: ${this.state.posts[property]}`);
}
}
render() {
return <div>
<div style={{ display: 'flex', justifyContent: 'center' }}>
<span> hey, i am left text </span>
<button onClick={this.Club}> Click Club </button>
</div>
</div>;
}
}
export default App;
【问题讨论】:
-
您需要将
this绑定到事件处理程序或仅使用箭头函数来解决问题。在此处阅读有关this绑定的更多信息 - freecodecamp.org/news/… -
是的,我怎么会忘记这个。谢谢 Dhilip。
-
参考这个stackoverflow.com/questions/45998744/…,你需要将你所有的事件处理函数绑定到
this。所以在你的情况下,onClick={this.Club.bind(this)}解决了这个问题。
标签: javascript reactjs for-in-loop