2016-11-22 39 views
0

在我的JSON文件中,我想要調用一些數據層。我的JSON數據,如我的getInitState所示,組織爲{forthem:[{articles:[]}]}。您也可以在https://emjayweb.github.io/portfolio/scripts/snippets.json查看我的數據。ReactJS調用JSON API

第一個函數,我使用變量fakeit按預期工作。然而,第二個函數,我打電話makeit來訪問我的articles數據不起作用。我收到一個Cannot read map of undefined錯誤。

我已經在下面列出了我的完整代碼以供審查。

getInitialState:function(){ 
    return {forname: '', forsym: '', fortitle: '', fulldata: {forthem:[ {articles: [] } ]} } 
}, 

componentDidMount:function(){ 
    var self = this; 
    $.getJSON('https://emjayweb.github.io/portfolio/scripts/snippets.json', function(snowden){ 
     self.setState({fulldata: snowden}); 
    }); 
}, 

render:function(){   
    return (<div id="madeforlist"> 
     <ul> 
      {this.state.fulldata.forthem.map(function(fakeit, i){ 
       return <li key={i}> 
          <i className="fa fa-plus-circle" aria-hidden="true"></i> 
          <span id="forname">{fakeit.therefore}</span> 
          <span className="pull-right">{fakeit.theresym}</span> 
         </li>})} 
      <ul> 
      {this.state.fulldata.forthem.articles.map(function(makeit, o){ 
       return <li key={o}>{makeit.article}</li> 
       })} 
      </ul> 
     </ul>  
    </div>); 
} 

回答

1

forthem是一個數組所以從字面上你需要傳遞一個索引來獲取數組文章

嘗試this.state.fulldata.forthem[0].articles.map()

this.state.fulldata.forthem.map(function(fakeit,i){ 

    fakeit.articles.map(function(article,j){ 

    }) 
}) 
+0

所以這個工程。但是,我似乎只能調用[0]。如果我用[1]替換它,我會得到一個'undefined'錯誤的文章。 – abrahamlinkedin

1

Cannot read map of undefined誤差是this.state.fulldata.forthem.articles.map()articlesundefined的原因。

我想知道GitHub.io是否支持跨域?如果沒有,這段代碼無法工作,因爲getJSON無法從你的要點中獲取數據。

+0

我能夠從我的Github上進行API調用。唯一的問題是,正如你所提到的,「articles」是未定義的。我不確定如何使用映射函數在React中定義它。編輯:明白了! – abrahamlinkedin