javascript - REACT 中的 UnCaughtType 错误, Hook 事件处理程序时的 js

标签 javascript jquery reactjs

我正在添加下拉列表并尝试将事件处理程序添加到每个项目并在 Button 中显示所选项目。当我尝试在 REACT.js 中的菜单项上 Hook 事件 onClick 时,我收到此错误。

未捕获类型错误:无法读取未定义的属性“subscribeToEvents”。下面是我的课

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:绑定(bind) 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));

解决方案 2:使用箭头函数,自动绑定(bind) this 的正确上下文。

this.state.data.cities.map(city => {
    if(city !== 'Location') {
        return <li onClick={this.subscribeToEvents.bind(this)} ><a href="#" >{city}</a></li>
    }
});

关于javascript - REACT 中的 UnCaughtType 错误, Hook 事件处理程序时的 js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38133516/

相关文章:

javascript - autocomplete.js 库不显​​示下拉菜单

javascript - react native 'Cannot read property of undefined' AsyncStorage

javascript - 将参数传递给作为参数传递给 jQuery 函数的函数

jQuery 在单击时仅选择当前元素

javascript - 通过使用 aws-sdk 在 s3 Bucket 上上传图像来 react native

javascript - 有没有办法在池化 A 型框架实体上启动 tick() 循环,或者我应该手动管理?

javascript - 如何查找数组中对象的出现次数

javascript - 使用jQuery promise模拟同步调用

reactjs - 如何使用 fetch get 方法从服务器检索数据并将其显示在表格中

javascript - setState() 导致 props 未定义