【问题标题】:Attempting to render to multiple attributes to a single JSX element from an object - React component尝试从一个对象渲染多个属性到单个 JSX 元素 - React 组件
【发布时间】:2019-09-05 16:23:43
【问题描述】:

我已经将一些数据保存到一个对象中的两个数组中,并且我想遍历这两个数组以获取单个 JSX 元素的两个属性。

我的具体用例是,我从用于渲染多个图像的 API 获取数据。 我在一个对象中有一个数组,它给了我图像 URL。 我在同一个对象中有另一个数组,它为我提供了同一图像的替代文本。 两个数组的长度相同。

我想遍历两个数组并将两者中的数据渲染到同一个图像元素。

我使用 .map 成功地将单个数组迭代到一个图像元素中,并渲染了我期望看到的尽可能多的图像。 然后我尝试使用 Object.entries,但最终还是得到了两个数组。

class Image extends React.Component {
  state = {
      photo: {
        img: [url1, url2, url3, url4],
        alt: [string1, string2, string3, string4] 
      },
    };

  render () {
    return(
      //currently only maps one array. Need to figure out how to map from two arrays
      this.state.photo.map((img, key) => {
        <Image img={this.state.photo.img} alt={this.state.photo.alt} key={key} />
      })
    )
  }
}

预期的结果是从对象照片中的两个数组 img 和 url 中获取的带有 url 和 alt 文本的几个图像组件。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您应该将数据结构更改为对象数组而不是两个数组。

    您的数组应如下所示:

    let images = [{image: url1, alt: alt1}, {image: url2, alt: al2 } ...etc.]
    

    现在映射这些变量会容易得多:

    this.state.images.map((x, index) => {
      <Image img={x.image} alt={x.alt} key={index} />
    })
    

    【讨论】:

      【解决方案2】:

      谢谢,你说得对,我的数据结构对我没有帮助。我最终用以下方法解决了这个问题

      class Image extends React.Component {
        state = {
            photo: [{image: url1, alt: alt1}, {image: url2, alt: al2 } ...etc],
          };
      
        render () {
          const images = this.state.photo.map((photo) =>
            <Image img={photo.image} alt={photo.alt} />
          );
      
          return (
            <div>
              {images}
            </div>
          )
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-12-14
        • 2022-12-19
        • 2022-11-01
        • 2020-01-17
        • 1970-01-01
        • 2018-03-07
        • 1970-01-01
        相关资源
        最近更新 更多