Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 未捕获(承诺中)类型错误:无法读取属性';handleClick';forEach循环中未定义的_Javascript_Reactjs - Fatal编程技术网

Javascript 未捕获(承诺中)类型错误:无法读取属性';handleClick';forEach循环中未定义的

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.

我有以下代码

articles_list.jsx 看看这是否能改变什么,但一切都一样


我应该在何处以及如何定义事件处理程序?

您忘记绑定
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>);
  })}