如何通过 React 按其键返回对象内容(JSON 文件)

how to return the object content (JSON file) by their key through React?

本文关键字:JSON 文件 对象 返回 React 何通过      更新时间:2023-09-26

我有一个包含多个停车场信息的 Json 字典文件。 车库名称是该车库详细信息的关键。数据结构是这样的

我正在尝试在 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;
  }
});