2017-10-22 33 views
-1

我正在構建一個簡單的新聞應用程序。 我從newsapi.org獲取API,並試圖在選擇組件的列表中顯示新聞源選項。傳播API JSON結果作爲選項列表

但是,它目前將每個新聞來源顯示爲一個新的單獨選項,而不是將其全部列在一個選項組件中。 (對不起,如果這很難理解,英語不是我的第一語言。因此,我已經包含屏幕截圖以及我的代碼)。

感謝所有提前。

componentDidMount() { 
    fetch('http://beta.newsapi.org/v2/sources?apiKey=XXX') 
    .then(results => { 
     return results.json(); 
    }).then(data => { 
     let sources = data.sources.map((src) => { 
      return(
       <div key={src.sources}> 
        <select className="form-control form-inline"> 
         <option value={src.id}>{src.name}</option> 
        </select> 
       </div> 
      ) 
     }) 
     this.setState({sources: sources}); 
    }) 
} 

render() { 
    return(
     <div className="container"> 
      <h2>Select a news source:</h2> 
      {this.state.sources} 
     </div> 
    ) 
} 
} 

+0

你的映射應該返回單個'選項',嵌套在父'select'下。你正在映射它的方式會返回單獨的'option'元素和它自己的'select'元素。 – char

+0

@char抱歉,我不完全明白。相當新的JavaScript。如果你不介意,你可以擴大一點嗎? –

+0

對於'data.sources'中的每個元素,您將返回 。最終結果是多個選擇/選項元素。你想要的是。 – char

回答

0

我看到@char已經解決了這個問題爲您服務。不過,這是代碼。 此外,最好只將「數據」存儲在狀態中,然後使用狀態在「渲染」功能內呈現視圖。

class MyComponent extends React.Component { 

    //other code 

    componentDidMount() { 
     fetch('http://beta.newsapi.org/v2/sources?apiKey=XXX') 
     .then(results => { 
      return results.json(); 
     }).then(data => { 
      this.setState({sources: data.sources}); 
     }) 
    } 

    render() { 
    return(
     <div className="container"> 
     <h2>Select a news source:</h2> 
     <SelectComponent sources={this.state.sources} /> 
     </div> 
    ) 
    } 
} 

const SelectComponent = ({sources})=>(
    <select className="form-control form-inline"> 
    {sources.map((source)=> 
     <option value={source.id} key={source.id} > {source.name} </option> 
    )} 
    </select> 
);