在REACT,js中钩子事件处理程序时出现UnCaughtType错误

UnCaughtType error in REACT,js when hooking the eventhandler

本文关键字:程序 错误 UnCaughtType 事件处理 REACT js      更新时间:2023-09-26

我正在添加下拉列表,并尝试将事件处理程序添加到每个项目,并在按钮中显示所选项目。当我尝试在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>
    }
});