【问题标题】:Mapping csv to display each items in the array in react映射 csv 以在反应中显示数组中的每个项目
【发布时间】:2019-12-03 00:25:31
【问题描述】:

我有一张产品表

所以我在这里有一列 product_images 包含 id 数组(用作图像的来源)。 使用道具我正在映射这些产品,如下所示:

render() {
        return (
            <>
                <ul className="row">
                    {this.props.products
                        .map(product => <li className="card col-md-4" key={product.id}>
                            <h2>{product.name}</h2>
                            <p>{product.description}</p>
                            <p>{product.sub_categories}</p>
                            <b>{product.created}</b>
                            {Object.keys(product.product_images)
                                .filter(v => product.product_images[v] != null)
                                .map(product_image =>
                                    <div key={product.product_images}>
                                        <img height='100%' alt='hello' 
                                        src={"IMAGE_PATH" + product.product_images[product_image]} />
                                    </div>
                                )}
                        </li>)}
                </ul>
            </>
        );
    }

这给了我每个产品。我还想得到的是数组中的每个 id 以在产品中显示多个图像。 我知道我在映射对象时做错了。 作为 javascript 和 react 的初学者,如果你们能帮助我,那就太好了。

我也愿意接受其他有趣的解决方案。谢谢

【问题讨论】:

  • 这里到底有什么问题?它工作正常吗?
  • 使用地图时,您可以将index 参数传递给map,例如map((product_image, index) =&gt; //etc)
  • 我现在收到此错误:警告:遇到两个孩子使用相同的密钥,1575290166391,1575290166394。密钥应该是唯一的,以便组件在更新时保持其身份。非唯一键可能会导致子项被重复和/或省略——这种行为不受支持,并且可能在未来的版本中发生变化。

标签: javascript mysql arrays reactjs mapping


【解决方案1】:

在我看来,您的 product_images 是产品图像 ID 的 CSV。如果是这种情况,请尝试:

{product.product_images.split(',')
  .filter(Boolean) // this is to filter out falsy values if necessary
  .map(product_image =>
      <div key={`${product.id}-${product_image}`}> // concat product id with the image id
          <img height='100%' alt='hello' src={`${IMAGE_PATH}${product_image}`} />
      </div>
  )}

【讨论】:

  • 这行得通。我不知道 CSV 是什么意思,但它是一个包含 id 的 varchar 列。非常感谢。
  • 它代表comma separated values。没问题。
【解决方案2】:
Object.values((product && product.product_images) || [])
  .filter(productImgArr => productImgArr !== null)
  .map(productImgArr => productImgArr.join(''))
  .map((product_image, index) =>
      <div key={`${product_image}-${index}`}>
          <img height='100%' alt='hello' 
          src={"IMAGE_PATH" + product_image} />
      </div>
  )

【讨论】:

  • 所以这是获取数组中每个整数的映射,包括逗号而不仅仅是两个 id。
  • 数组中的整数是什么意思,product_images[index] 是什么意思?我修改了我认为应该可行的答案
  • 是的,product.product_images[index] 返回数组中的每个值,如:1,5,7,5,2,9,0,1,6,6,3,9,1, ,,1,5,7,5,2,9,0,1,6,6,3,9,4 对于每个产品。不是 1575290166391 和 1575290166394。
猜你喜欢
  • 2020-08-20
  • 1970-01-01
  • 2018-11-16
  • 2023-01-03
  • 1970-01-01
  • 2021-11-19
  • 2021-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多