我有一个反应原生的功能
_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();
},
我试图在一个组件中获取文章标题,但我很难这样做。我怎样才能做到这一点?谢谢!
答案 0 :(得分:2)
首先,您需要定义一个状态,用于存储您的标题。您可以使用类属性来执行此操作:
class TitleExample extends Component {
state = { title: "" };
}
然后你需要调用你的fetch函数。您可以在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 Native无关,所以我建议您阅读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>
);
}
}