2016-06-30 6 views
1

ドロップダウンリストを追加して、各アイテムにイベントハンドラを追加しようとしています。選択したアイテムをButtonに表示しようとしています。 REACT.jsでこのエラーが発生します。REACTのUnCaughtTypeエラー、イベントハンドラをフックするときのjs

未キャッチタイプエラー:未定義のプロパティ 'subscribeToEvents'を読み取ることができません。ここに私のクラスでは、あなたの問題はthisはあなたが.map()に渡している関数の内部で定義されていないということです

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>); 
 

 
    } 
 
}

答えて

2

を下回っています。

解決策1:これの正しいコンテキストをバインドします。

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:自動的thisの正しいコンテキストをバインドする矢印機能を使用します。

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

解決策1は機能しませんでしたが、解決策2が機能しました。ソリューションに感謝します。 –

関連する問題