首先,您需要定义一个状态来存储您的标题。你可以做一个类属性:
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>
);
}
}
好的,谢谢你! @Kerumen然后我将如何能够遍历JSON中的所有项目,而不是仅仅调用第一个项目,是否有像.each或其他东西? – dylan
@DylanSteck我编辑了我的答案添加此。 – Kerumen