2016-12-01 64 views
1

我一直在嘗試從API中獲取JSON數據並使用map()函數顯示它。不幸的是,API返回的數據格式爲:{「type」:...,「value」:...}。第二個對象包含一個包含我想要訪問的數據的數組。使用Fetch API和JavaScript中的映射()顯示JSON數據/ Reactjs

有沒有一種方法可以訪問(或單出)只是API中的第二個對象?然後我可以在其上運行map()。見下面的代碼。目前返回錯誤:this.state.jokes.map不是函數

P.S.該代碼完美地工作在封裝在數組中的API上,例如http://jsonplaceholder.typicode.com/posts

class JokeList extends React.Component { 

    constructor() { 
     super(); 
     this.state = {jokes:[]}; 

    } 

    componentDidMount() { 
     fetch(`http://api.icndb.com/jokes`) 
      .then(result => result.json()) 
      .then(jokes => this.setState({jokes})) 
    } 

    render() { 

     return (
      <div> 
       {this.state.jokes.map(joke => 
         <div key={joke.id}> {joke.joke} </div>)} 
      </div> 
     ); 
    } 
} 

回答

2

嘗試使用

fetch(`http://api.icndb.com/jokes`) 
    .then(result => result.json()) 
    .then(jokes => this.setState({jokes: jokes.value})) 

代替。

這是因爲來自API的響應是這樣的:

{ 
    "type": "...", 
    "value": [the value you want], 
} 

您希望value鍵的值,因爲這是你以後使用的是什麼。