json - 返回 JSON 并打印出 reactJS
问题描述
您会认为从 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 | });
我怎样才能解决这个问题?
解决方案
axios.get(' http://api.drn1.com.au/api-access/news ') 返回如下:
{'news': [{}, {}, ...]}
所以你应该迭代 data.news,而不是数据。
推荐阅读
- angular - 根据字段信息显示或隐藏图标
- maven - Maven 覆盖版本标签
- java - Kotlin 方法中的泛型
- reactjs - 循环超出最大调用堆栈大小
- javascript - 如何将 babel 与 webpack 一起使用以实现 ie11 兼容性
- java - 无法在 java web servlet 中直接调用 ActiveMQConnection 类
- sql-server - 仅投射为日期
- postgresql - PostgreSQL 升级到 12+ 将哈希连接更改为慢速嵌套循环
- c++ - 从异构大括号初始值设定项列表创建树
- python - 记录 - 如何将相同的记录器用作不同文件的类?