2016-11-13 100 views
0

我有一個函數在反應本土本土作出反應,呼籲職能

_onPressButtonGET: function() { 
    fetch("https://newsapi.org/v1/articles?source=techcrunch&apiKey=[YOUR_API_KEY]", {method: "GET"}) 
    .then((response) => response.json()) 
    .then((responseData) => { 
//    AlertIOS.alert(
//     "Latest Story: TechCrunch", 
//     "" + responseData.articles[0].title 
//   ) 
responseData.articles[0].title 
    }) 
    .done(); 
}, 

,我試圖讓一個組件文章標題,但我有麻煩這樣做。我怎樣才能做到這一點?謝謝!

回答

2

首先,您需要定義一個狀態來存儲您的標題。你可以做一個類屬性:

class TitleExample extends Component { 

    state = { title: "" }; 

} 

然後,你需要調用你的獲取函數。你可以做到這一點在componentWillMount因此數據將組件的安裝之前獲取的:

class TitleExample extends Component { 

    state = { title: "" }; 

    componentWillMount() { 
    fetch("https://newsapi.org/v1/articles?source=techcrunch&apiKey=[YOUR_API_KEY]") 
    .then((response) => response.json()) 
    .then((responseData) => this.setState({ title: responseData.articles[0].title })); 
    } 

} 

最後,你可以使你的標題:

class TitleExample extends Component { 

    state = { title: "" }; 

    componentWillMount() { 
    fetch("https://newsapi.org/v1/articles?source=techcrunch&apiKey=[YOUR_API_KEY]") 
    .then((response) => response.json()) 
    .then((responseData) => this.setState({ title: responseData.articles[0].title })); 
    } 

    render() { 
    return (
     <View> 
     <Text>{this.state.title}</Text> 
     </View> 
    ); 
    } 

} 

你正在做一些非常基本的,不相關反應本機特別如此,我建議您閱讀React網站上的state docs

編輯:

我要呈現的所有文章,然後你可以遍歷所有的人都存儲在狀態的呈現:

class TitleExample extends Component { 

    state = { articles: [] }; 

    componentWillMount() { 
    fetch("https://newsapi.org/v1/articles?source=techcrunch&apiKey=[YOUR_API_KEY]") 
    .then((response) => response.json()) 
    .then((responseData) => this.setState({ articles: responseData.articles })); 
    } 

    render() { 
    return (
     <View> 
     {this.state.articles.map(article => (
      <Text>{article.title}</Text> 
     ))} 
     </View> 
    ); 
    } 

} 
+0

好的,謝謝你! @Kerumen然後我將如何能夠遍歷JSON中的所有項目,而不是僅僅調用第一個項目,是否有像.each或其他東西? – dylan

+0

@DylanSteck我編輯了我的答案添加此。 – Kerumen