我有一个 Json 字典文件,其中包含几个 parking 场信息。车库名称是了解该车库详细信息的关键。 the data structure is like this
我正在尝试在 React 中编写一个 for 循环,以列表格式将所有车库信息拉到我的网页上。
我的代码:
MyComponents.Garage = React.createClass({
render: function() {
var garage = this.props.garage
console.log(garage)
return (
<li className="card-content">
TODO: This is a component about a garage whose
raw data is //{JSON.stringify(this.props.garage)}
<MyComponents.GarageTitle
title={this.props.garage.friendlyName}/>
<MyComponents.GarageSpaces
open={this.props.garage.open_spaces}
total={this.props.garage.total_spaces}/>
<MyComponents.GarageRates
rates={this.props.garage.rates}/>
<MyComponents.GarageHours
hours={this.props.garage.hours}/>
</li>
);
}
});
MyComponents.Garages = React.createClass({
render: function(){
console.log(this.props.garage)
for (var key in this.props.garage){
console.log(this.props.garage[key])
return (
<ul>
<MyComponents.Garage garage={this.props.garage[key]}/>
</ul>
);
}
}
});
我首先将 Json 数据传递给 Mycomponent.Garages 并在内部运行 for 循环,并调用 Mycomponent.Garage 来获取该 Garage 的每个详细信息。
但我的问题是我只能运行第一个车库,它不会继续循环剩余的车库。
有人可以帮助我完成任务吗?
谢谢
最佳答案
在 for in 循环中使用 return 是行不通的,但你已经接近正确了!相反,尝试创建车库节点数组:
MyComponents.Garages = React.createClass({
render: function(){
garageNodes = [];
for (var key in this.props.garage){
console.log(this.props.garage[key])
garageNodes.push(
<ul>
<MyComponents.Garage garage={this.props.garage[key]}/>
</ul>
);
}
return garageNodes;
}
});
关于javascript - 如何通过 React 通过 key 返回对象内容(JSON 文件)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35208263/