2017-10-28 24 views
1

誰能幫我爲什麼已瞭解這句話無法讀取的未定義的屬性「國家」在一個地方,在另一個可以讀取

if (this.state.ind == index) {return <div key={index}> 

它顯示錯誤,但是當我在打印this.state.ind它工作沒有問題?

var Countries = React.createClass({ 
getInitialState: function() { 
    return { 
     countries: [], 
     ind: 0, 
     loaded: false, 
    }; 
}, 

componentDidMount: function() { 
    this.getCountry(); 
}, 

打電話給JSON文件

getCountry: function() { 
    // take this to variable me -> used inside AJAX-callback functions 
    var me = this; 
    // create ajax call to json file, handle done and fail 
    $.ajax({ 
     url: 'json/countries.json', 
     cache: false, 
     dataType: 'json' 
    }).done(function(data) { 
     me.setState({countries: data.asia, loaded:true}); 
    }).fail(function(jqXHR, textStatus, errorThrown) { 
     me.setState({infoText: textStatus+":"+errorThrown}); 
    }); 
}, 

代碼按鈕

handleClick() { 
this.setState({ind: this.state.ind + 1}); 
}, 


render: function() {  
    return (
     <div> 
      {this.state.countries.map(function(country,index){ 

這裏不起作用

   if (this.state.ind == index) {return <div key={index}> 
       <p>{country.name}</p> 
       <p>{country.capital}</p> 
       </div>;} 
      })} 

這裏工作

  <p>{this.state.ind}</p> 
      <button onClick={this.handleClick}>Next</button> 
     </div> 
    ); 
} 

}); 

回答

0

使用下面的代碼的if-else在JSX

render: function() {  
    return (
     <div> 
      {this.state.ind == index && <div key={index}> 
      <p>{country.name}</p> 
      <p>{country.capital}</p> 
      </div>} 
     .... 
0

不能的if/then/else塊在JSX使用我們不能使用。更好的形式是將列表預先過濾爲只有在映射語句之前要呈現的內容。

render: function() { 
    const testInd = this.state.ind; 
    const indStates = this.state.countries.filter(function(c, ind) { return c.ind === testInd }); 
    return (
     <div> 
      { indStates.map(function(country) { 
       <div key={index}> 
        <p>{country.name}</p> 
        <p>{country.capital}</p> 
       </div> 
      })} 
     </div> 
    })); 
} 

在沒有測試的情況下鍵入了它,但它看起來像你想要的。

+0

我很抱歉問,但現在它告訴「不能讀取未定義的屬性'地圖',我只是不能得到什麼錯誤,因爲反應對我來說是新的。 – Seiggailion

+0

@Seiggailion我認爲這會解決它。 – billjamesdev

+0

我今天猜測,這可能有幫助,但之後,它抱怨「未捕獲TypeError:不能讀取未定義在eval的屬性'狀態'在此行」const indStates = this.state.countries.filter(function(c,ind) {return c.ind === this.state.ind});「。我只是不能得到什麼是錯誤的,無論我讀了多少和嘗試=( – Seiggailion

相關問題