javascript - 如何通过 React 通过 key 返回对象内容(JSON 文件)?

标签 javascript html dom reactjs

我有一个 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/

相关文章:

javascript - 找不到express.js 文件

javascript - 正则表达式限制输入文本框

javascript - jquery 如何使用子项获取父文本?

jquery - 打开页面时自动展开 div

javascript - 仅将 HTML 加载到 IFRAME 中

javascript - 为什么带有名称的表单被添加到文档属性中

html - 另一个 block 级元素上的 margin-top

javascript - 如何在不导入组件ReactJS的情况下传递状态?

javascript - 立即访问对象的属性

javascript - 触摸滚动在某些设备上不起作用