Javascript 从映射返回的React渲染数组
我面临的问题与非常类似,但我使用承诺获取数据,并希望在数据通过时将其呈现到DOM中。Javascript 从映射返回的React渲染数组,javascript,dictionary,promise,reactjs,lodash,Javascript,Dictionary,Promise,Reactjs,Lodash,我面临的问题与非常类似,但我使用承诺获取数据,并希望在数据通过时将其呈现到DOM中。console.log()正确显示所有项目。我认为我的问题是lodash.map返回一个元素数组,因此我试图调用this.renderItems()来进行渲染(但是renderItems()似乎不存在)。我是否在做一些非常规的事情,是否有更简单的方法,是否有等效的函数来替换我的renderItems() renderaticleheadline:function(文章){ log('renderaticlehea
console.log()
正确显示所有项目。我认为我的问题是lodash.map返回一个
元素数组,因此我试图调用this.renderItems()
来进行渲染(但是renderItems()
似乎不存在)。我是否在做一些非常规的事情,是否有更简单的方法,是否有等效的函数来替换我的renderItems()
renderaticleheadline:function(文章){
log('renderaticleheadline',article.headline);
返回(
{文章标题}
)
},
render:function(){
返回(
{
这是我的(
this.fetchFrontPageArticles().then(数据=>{
map(数据,this.renderaticleheadline)
})
)
}
);
}
应该是这样的
getInitialState: function() {
return {
items: []
};
},
renderArticleHeadline: function(article) {
return (
<li>
{article.headline}
</li>
);
},
componentDidMount: function() {
this.fetchFrontPageArticles().then(data => {
this.setState({
items: data
});
});
},
render: function() {
var items = lodash.map(this.state.items, this.renderArticleHeadline);
return (
<div>
<ul>
{items}
</ul>
</div>
);
}
getInitialState:function(){
返回{
项目:[]
};
},
RenderArticlHeadline:函数(文章){
返回(
{文章标题}
);
},
componentDidMount:function(){
this.fetchFrontPageArticles().then(数据=>{
这是我的国家({
项目:数据
});
});
},
render:function(){
var items=lodash.map(this.state.items,this.renderaticleheadline);
返回(
{items}
);
}
请注意,read记住,
render
是同步调用的,而您的fetch
是异步的。因此,在返回数据时,render
函数已经完成。因此,什么也不会显示。IIRCrender
不应该调用fetch
,控制流应该是反向的。@Bergi它不是一个IIRC(React只是一个视图库)根据常识:)这里的问题可能是renderItems提供了一个承诺。是的,这看起来更像是fetchFrontPageArticles调用setStateFWIW,如果RenderArticlHeadlinegetInitialState: function() {
return {
items: []
};
},
renderArticleHeadline: function(article) {
return (
<li>
{article.headline}
</li>
);
},
componentDidMount: function() {
this.fetchFrontPageArticles().then(data => {
this.setState({
items: data
});
});
},
render: function() {
var items = lodash.map(this.state.items, this.renderArticleHeadline);
return (
<div>
<ul>
{items}
</ul>
</div>
);
}