我是React的新手,在尝试从API映射一些数据时就抛出了。我已经将状态设置为数组,但是仍然出现此错误。
import React, { Component } from 'react';
import axios from 'axios';
class Test extends Component {
state = {
articles: [],
}
componentDidMount() {
axios.get('https://newsapi.org/v2/top-headlines?country=us&apiKey=ef678d80cc70495184c2bf95d4576c9b')
.then(response => {
const articles = response.data;
this.setState({ articles });
})
}
render() {
return (
<div>
<ul>
{this.state.articles.map(article => <li><a href={`${article.url}`}>{article.title}</a></li>)}
</ul>
</div>
)
}
}
export default Test;
答案 0 :(得分:2)
尝试更改
const articles = response.data;
到
const articles = response.data.articles;
这是因为api返回的是JSON输出,其中包含文章键中的响应。
答案 1 :(得分:0)
import React, {Component} from 'react';
import axios from 'axios';
class Test extends Component {
state = {
articles: [],
}
componentDidMount() {
axios.get('https://newsapi.org/v2/top-headlines?country=us&apiKey=ef678d80cc70495184c2bf95d4576c9b')
.then(response => {
const articles = response;
this.setState({articles:articles.articles});
}) }
render() {
return (
<div>
<ul>
{this.state.articles.map(article =>
<li><a href={`${article.url}`}>{article.title}</a>
</li>)}
</ul>
</div>
) }
}
export default Test;
答案 2 :(得分:0)
import React, {Component} from 'react'; import axios from 'axios';
class Test extends Component {
state = {
articles: [],
flag:false
}
componentDidMount() {
axios.get('https://newsapi.org/v2/top-headlines?country=us&apiKey=ef678d80cc70495184c2bf95d4576c9b')
.then(response => {
const articles = response.data;
this.setState({articles,flag:true});
}) }
render() {
let data = flag === false?"Loading...":this.state.articles.map(article => <li><a href={`${article.url}`}>{article.title}</a></li>)
return (
<div>
<ul>
{data}
</ul>
</div>
) }
}
export default Test;