我试图通过构建一个简单的web应用程序来学习ReactJS,该应用程序对模拟api进行几次ajax调用并将结果呈现到页面上。
到目前为止,我可以通过适当使用componentDidMount成功地对模拟api进行ajax调用。响应文本是一个JSON对象,我在其中存储了几个状态数组,例如:
var newTitle = this.state.title.slice();
newTitle.push(myObject[x].title);
this.setState({title:newTitle})
var newBody = this.state.body.slice();
newBody.push(myObject[x].body);
this.setState({body:newBody})
myObject是存储解析的JSON响应的对象。
通过执行以下操作,我可以成功地呈现一个数组(即标题):
<FeedController title={this.state.title}/>
class FeedController extends Component{
render({
return(
{this.props.title.map(function(element,i){
return <FeedItem title={element} />
})}
);
});
}
class FeedItem extends Component{
render({
return(
<div>
Title: {this.props.title}
</div>
);
});
我循环遍历标题状态,并在每次迭代中显示一个FeedItem。然而,我的问题和问题是,如何从多个支柱数组中呈现一个组件?例如,我希望title1与body1等一起显示。
我想我会把头衔和身体当作道具来做,但我无法想出如何将两者都映射出来,也无法呈现出结果。理想情况下,我的FeedItem组件如下所示:
class FeedItem extends Component{
render({
return(
<div>
Title: {this.props.title}
<br />
Body: {this.props.body}
<br /><br />
</div>
);
});
}
发布于 2017-05-26 15:07:02
如果知道数组的长度相同,则可以使用相同的索引来获取匹配的数据。
<FeedController title={this.state.title} body={this.state.body}/>
class FeedController extends Component{
render({
return(
{this.props.title.map(function(element,i){
return <FeedItem title={element} body={this.props.body[i]} />
})}
);
});
}
class FeedItem extends Component{
render({
return(
<div>
Title: {this.props.title}
<br />
Body: {this.props.body}
<br /><br />
</div>
);
});
}
或者,您可以在将数据传递给FeedController之前将其合并。
render(){
let data = this.state.title.map( (title, i) => {
return {
title: title,
body: this.state.body[i]
}
}
return <FeedController data={data} />
}
class FeedController extends Component{
render({
return(
{this.props.data.map( (data,i) => {
return <FeedItem title={data.title} body={data.body} />
})}
);
});
}
class FeedItem extends Component{
render({
return(
<div>
Title: {this.props.title}
<br />
Body: {this.props.body}
<br /><br />
</div>
);
});
}
https://stackoverflow.com/questions/44204615
复制相似问题