【发布时间】:2017-11-06 23:04:06
【问题描述】:
我有以下组件:
articles_list.jsx
import React from 'react';
import './articles_list.css';
export default class ArticlesList extends React.Component {
constructor(props) {
super(props);
this.state = {
articles: null
}
}
componentWillMount() {
fetch('/articles_all')
.then(res => res.json())
.then(json => {
this.setState({
articles: json.articles
});
});
}
render() {
var teste = () => {
if (this.state.articles === null) {
return(<div>No articles</div>)
} else {
{this.state.articles.forEach( function(element, index) {
console.log(element);
return <div key={index}>{element.title}</div>;
})}
}
}
return(
<div className="articles_list">
<div className="articles_list_title">
ARTICLES
</div>
<div>{teste()}</div>
</div>
);
}
}
虽然 JSON 请求工作正常并返回一个包含五个 JSON 对象的数组,但它们只是不渲染!
我是 ReactJS 的新手,阅读(并观看)了很多教程,但我似乎遗漏了一些东西。
有什么建议吗?
【问题讨论】:
-
Array.prototype.forEach什么都不返回,你想要Array.prototype.map代替。
标签: javascript json reactjs