在REACT,js中钩子事件处理程序时出现UnCaughtType错误
UnCaughtType error in REACT,js when hooking the eventhandler
我正在添加下拉列表,并尝试将事件处理程序添加到每个项目,并在按钮中显示所选项目。当我尝试在REACT.js的菜单项上挂钩onClick事件时,我得到了这个错误。
Uncaught TypeError: Cannot read属性'subscribeToEvents' of undefined。下面是我的class
export default class LocationList extends React.Component {
constructor(props)
{
super(props);
this.state={selectedIndex:"Location",
data:{
cities: ["Location","Bangalore","Chennai","Pune"]
}
};
}
getInitialState()
{
}
subscribeToEvents(event)
{
}
render()
{
var titleVal = this.state.selectedIndex;
console.log(titleVal);
return(
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" id="locationDropDown" type="button" data-toggle="dropdown">{titleVal}
<span class="caret"></span></button>
<ul class="dropdown-menu">
{ this.state.data.cities.map(function(city) {
if(city !='Location')
{
return <li onClick={this.subscribeToEvents.bind(this)} ><a href="#" >{city}</a></li>
}
})
}
</ul>
</div>);
}
}
您的问题是this
在您传递给.map()
的函数中未定义。
解决方案1:绑定this的正确上下文
this.state.data.cities.map(function(city) {
if(city !== 'Location') {
return <li onClick={this.subscribeToEvents.bind(this)} ><a href="#" >{city}</a></li>
}
}.bind(this));
方案二:使用箭头函数,自动绑定正确的this
上下文。
this.state.data.cities.map(city => {
if(city !== 'Location') {
return <li onClick={this.subscribeToEvents.bind(this)} ><a href="#" >{city}</a></li>
}
});
相关文章:
- Rails第一个应用程序错误——Errno::ENOENT
- AngularJS:未知的提供程序错误
- webpack:在MacOS上很好,在linux上加载程序错误
- 获取解析值的未知提供程序错误
- React应用程序错误'未捕获的ReferenceError:React未定义'
- IE和GMap API 2包装程序错误
- 无法将节点邮件程序错误响应从节点.js发送到角度.js
- 密钥斗篷未知提供程序错误
- 谷歌浏览器扩展名$.ajax发布事件处理程序错误
- j查询动态事件处理程序错误
- 节点 JS 取消处理程序错误事件
- Chrome 扩展程序和保管箱投放保护程序错误
- 未知提供程序错误 - AngularJS 应用程序问题
- 车把自定义帮助程序错误:“options.fn 不是函数”
- 在 yeoman 中使用动画模块编译 AngularJS 应用程序会给出未知的提供程序错误
- 如何使用 JavaScript 访问 CouchDB?标准操作程序错误
- Angularjs.获取控制器的范围.未知的提供程序错误
- Kendo UI移动滚动程序错误
- Angular js:->访问解析属性时,angular引发未知提供程序错误
- 在遍历光标和更新文档时,连接因应用程序错误而关闭