代码之家  ›  专栏  ›  技术社区  ›  user13286

在React render中循环对象

  •  1
  • user13286  · 技术社区  · 6 年前

    我在React应用程序中循环使用了一些JSON。在JSON中,我循环使用一个包含多个图像的对象。我想在这些图像中循环并渲染它们。我试过的是:

    const locations = [
      {
        "name": "First Location",
        "photos": [
          {
            "url": "http://placehold.it/250x250",
          }, {
            "url": "http://placehold.it/250x250",
          }
        ]
      }, {
        "name": "Second Location",
        "photos": [
          {
            "url": "http://placehold.it/250x250",
          }, {
            "url": "http://placehold.it/250x250",
          }
        ]
      }
    ]
    
    const element = (
      <div className="community-list">
        {locations && locations.map((location, index) => (
          <div key={index} className="location">
            <h2>{location.name}</h2>
            {Object.keys(location.photos).map(function(key) {
              return <img src="{location.photos[url]}" />;
            })}
          </div>
        ))}
      </div>
    );
    ReactDOM.render(element, document.getElementById('mountNode'));

    但是这给了我两张破碎的图片

    2 回复  |  直到 6 年前
        1
  •  2
  •   Gangadhar Gandi    6 年前

    实际问题是,img标记有一个额外的双引号。 删除括住大括号的双引号。将显示您的图像

    <img src={location.photos[url]} />
    
        2
  •  1
  •   Edrian    6 年前

    你想做的是:

    const locations = [
      {
        "name": "First Location",
        "photos": [
          {
            "url": "http://placehold.it/250x250",
          }, {
            "url": "http://placehold.it/250x250",
          }
        ]
      }, {
        "name": "Second Location",
        "photos": [
          {
            "url": "http://placehold.it/250x250",
          }, {
            "url": "http://placehold.it/250x250",
          }
        ]
      }
    ]
    
    const element = (
      <div className="community-list">
        {locations && locations.map((location, index) => (
          <div key={index} className="location">
            <h2>{location.name}</h2>
            {location.photos.map(function(photo) {
              return <img src="{photo.url}" />;
            })}
          </div>
        ))}
      </div>
    );
    ReactDOM.render(element, document.getElementById('mountNode'));
    

    这将遍历 photos a数组 location ,然后使用 url 的节点 photo 反对。