2016-11-13 69 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