【发布时间】:2019-08-03 04:36:49
【问题描述】:
你会认为从 JSON 文件返回数据很简单,但是我的尝试失败了。
基本概念如下
class News extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount() {
axios.get('http://api.drn1.com.au/api-access/news')
.then(({ data })=> {
this.setState({
data: data
});
});
}
render() {
return (
<Container maxWidth="lg">
<Helmet>
<meta charSet="utf-8" />
<title>DRN1 :: Latest News</title>
<link rel="canonical" href={document.location} />
</Helmet>
<ComingSoon />
{this.state.data.map(news => <div>{news.title+' '+news.url}</div>)}
</Container>
);
}
}
export default News;
但它似乎正在抛出错误。
TypeError: this.state.data.map is not a function
News.render
src/components/News.js:67
64 | <title>DRN1 :: Latest News</title>
65 | <link rel="canonical" href={document.location} />
66 | </Helmet>
> 67 | <ComingSoon />
| ^ 68 |
69 | {this.state.data.map(news => <div>{news.title+' '+news.url}</div>)}
70 |
View compiled
▶ 17 stack frames were collapsed.
(anonymous function)
src/components/News.js:53
50 | componentDidMount() {
51 | axios.get('http://api.drn1.com.au/api-access/news')
52 | .then(({ data })=> {
> 53 | this.setState({
| ^ 54 | data: data
55 | });
56 | });
我该如何解决这个问题?
【问题讨论】:
-
注释掉有
.map的那一行,去掉错误,加上console.log(this.state.data),看看是不是数组 -
@MoIsmat 以下工作的 console.log(this.state.data.news);但是我如何打印它(foreach?)
-
@RussellHarrower 能否提供控制台登录时在 this.state.data 中获得的内容