本文介绍了基于对象列表呈现ReactJS组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下组件:
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对象,它们只是不渲染!
Although the JSON request is working fine and returning an array with five JSON objects, they just don't render!
我是ReactJS的新手并阅读(并观看)了很多教程,但似乎我遗漏了一些东西。
I am new to ReactJS and read (and watched) lots of tutorials, but it seems I am missing something.
有什么建议吗?
推荐答案
在forEach内部返回语句没有' t返回值而不是像 continue
语句,你需要使用map
return statement inside a forEach doesn't return the value instead it acts like a continue
statement, you need to make use of map
var teste = () => {
if (this.state.articles === null) {
return(<div>No articles</div>)
} else {
{this.state.articles.map( function(element, index) {
console.log(element);
return <div key={index}>{element.title}</div>;
})}
}
}
否则如果你想与forEach一起你需要修改你的代码,如
else if you want to go with forEach you need to modify your code like
render() {
var teste = []
if (this.state.articles === null) {
teste.push(<div>No articles</div>)
} else {
{this.state.articles.forEach( function(element, index) {
console.log(element);
teste.push( <div key={index}>{element.title}</div>);
})}
}
}
return(
<div className="articles_list">
<div className="articles_list_title">
ARTICLES
</div>
<div>{teste}</div>
</div>
);
}
这篇关于基于对象列表呈现ReactJS组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!