2017-08-24 19 views
0

我想映射通過一個數組,並創建鏈接,將更新狀態。當我繪製整個數組,然後創建鏈接我得到:handleClick當映射一個數組時反應

類型錯誤:無法讀取屬性「handleClick」的未定義

var FilterList = React.createClass({ 
 
    handleClick : function(e, list){ 
 
      this.props.callbackFromParent(list); 
 
       this.setState({showing : list}); 
 
      }, 
 
    render: function() { 
 
      if(this.props.sdata){ 
 
      var seasons =''; 
 
      seasons = this.props.sdata.Seasons.map(function(season, i) { 
 
       if(i < 30) { 
 
       var playkey = season.mediaId; 
 
       var name = season.Season; 
 
      return (
 
      <li> <a href="#" onClick={(e) => this.handleClick(e, {playkey})}>{name}</a></li> 
 
     ); 
 
     }else{ 
 
      return (<div key={playkey}></div>); 
 
     } 
 
     }); 
 
     return (
 
     <Row className="singleChannelSeasonsList"> 
 
     <Grid> 
 
      <Col md={12}> 
 
       <ul className="seasons"> 
 
       {seasons} 
 
       </ul> 
 
      </Col> 
 
     </Grid> 
 
    </Row> 
 
    ); 
 
      } else { 
 
    return (
 

 
     <Row className="singleChannelSeasonsList"> 
 
     <Grid> 
 
      <Col md={12}> 
 
       <ul className="seasons"> 
 
       <li><a href="#" className="activeItem" onClick={(e) => this.handleClick(e, "list")}>All</a></li> 
 
        <li> <a href="#" onClick={(e) => this.handleClick(e, "category/Entertainment")}>Entertainment</a></li> 
 
        <li><a href="#" onClick={(e) => this.handleClick(e, "category/Health%20&%20Wellness")}>Health &amp; Wellness</a></li> 
 
        <li> <a href="#" onClick={(e) => this.handleClick(e, "category/Opinion")}>Opinion</a></li> 
 
       </ul> 
 
      </Col> 
 
     </Grid> 
 
    </Row> 
 
    ); 
 
    } 
 
    } 
 
}); 
 
export default FilterList;

我該如何映射通過數據並生成handleclick鏈接。 {this}是綁定的,它在我沒有this.props.sdata時有效。謝謝!

+0

的可能的複製(https://stackoverflow.com/questions/45010544/react-cannot-read-property- [作出反應,儘管正確結合 '無法讀取的未定義的屬性']的,不確定的,儘管糾正結合) –

回答

0

您還沒有{this}到this.props.sdata.Seasons.map(() => {})呢!

它應該是:

render: function() { 
    if(this.props.sdata){ 
    var seasons =''; 
    seasons = this.props.sdata.Seasons.map((season, i) => { 
     //... 
    }); 
    } else { 
    //... 
    } 
    //... 
} 
0

如果我正確理解你的問題,你需要把它綁定到你的事件處理程序:

... 
onClick={this.handleClick.bind(this)} 
... 
1

問題是「本」的價值關鍵字由函數的調用方式決定。 「this」在「map()」的匿名函數中被調用。所以「這個」將是未定義的。

解決方案:

  1. 綁定() 「這個」 匿名功能

this.props.sdata.Seasons.map(function(season, i) { 
 
    //....blah blah blah  
 
    }.bind(this));

  • 集「這「到」map()「函數的第二個參數
  • this.props.sdata.Seasons.map(function(season, i) { 
     
         //....blah blah blah 
     
        },this);