Javascript 未捕获(承诺中)类型错误:无法读取属性';handleClick';forEach循环中未定义的
我有以下代码 articles_list.jsx 看看这是否能改变什么,但一切都一样Javascript 未捕获(承诺中)类型错误:无法读取属性';handleClick';forEach循环中未定义的,javascript,reactjs,Javascript,Reactjs,我有以下代码 articles_list.jsx 看看这是否能改变什么,但一切都一样 我应该在何处以及如何定义事件处理程序?您忘记绑定forEach函数,因此出现了错误,因为,这个forEach函数中的将引用它自己的上下文,其中未定义handleClick,而不是React组件,或者使用绑定(this)类似于 {this.state.articles.forEach( function(element, index) { console.log(element); teste.
我应该在何处以及如何定义事件处理程序?您忘记绑定
forEach
函数,因此出现了错误,因为,这个forEach函数中的将引用它自己的上下文,其中未定义handleClick
,而不是React组件,或者使用绑定(this)
类似于
{this.state.articles.forEach( function(element, index) {
console.log(element);
teste.push(<div onClick={this.handleClick} className="articles-menu-item" key={index.toString()}>{element.title}</div>);
}.bind(this))}
在forEach中使用箭头函数。LSS,函数声明在不同的上下文中执行,具有不同的执行上下文,因此此值不同,通常为窗口(全局执行上下文)或在严格模式下未定义。再次感谢!我没有忘记。我只是不知道我必须这么做。对ReactJS完全陌生,从错误中学习。在未来的任何suc案例中,一定要看看绑定是否正确。我肯定会这样做。谢谢
handleClick = (e) => {
e.preventDefault();
// Do something else
}
{this.state.articles.forEach( function(element, index) {
console.log(element);
teste.push(<div onClick={this.handleClick} className="articles-menu-item" key={index.toString()}>{element.title}</div>);
}.bind(this))}
{this.state.articles.forEach( (element, index) => {
console.log(element);
teste.push(<div onClick={this.handleClick} className="articles-menu-item" key={index.toString()}>{element.title}</div>);
})}