【问题标题】:React, how to render static json data with different keysReact,如何用不同的键渲染静态 json 数据
【发布时间】:2020-03-16 00:14:42
【问题描述】:

这是一个静态 json 数据的例子。

我无法从数组中渲染“promoimage”。

我不是 100% 确定如何解决这个问题。我在玩arround,想检查'promoimage'是否存在,但没有返回任何东西? 任何建议如何实现这一目标?

[
    {
        "title": "some title",
        "promoimage": "image.jpg",
        "url": "#"
    },
    {
        "title": "some title",
        "image": "example.jpg",
        "url": "#"
    },
{
        "title": "some other title",
        "promoimage": "image.jpg",
        "url": "#"
    },
    {
        "title": "title",
        "image": "example.jpg",
        "url": "#"
    },
]

我的 React 组件:

import products from '../product-data.json';
...
export const CustomSlider = () => {
   // Here I'm using react-slick 

 const productList = products.map((product, i) => {
    const uniqueItems = [];
    if (uniqueItems.indexOf(product.imageone) === -1) {
        uniqueItems.push(product.imageone);
    }

   /* This works
     if (product.hasOwnProperty('promoimage')) {
      return true
    }
   */

         return <Product key={i} {...product} />;
        }
    );

  return (
      <Slider>
        {productList}
      </Slider>  
  )
}

【问题讨论】:

    标签: arrays json reactjs object


    【解决方案1】:

    代码将所有对象键作为道具发送到Product。特别是{...product}这部分扩展成这样:

    <Product 
      key={i}
      title="some title"
      promoimage="image.jpg"
      url="#"
    />
    

    这称为传播。

    现在,我怀疑&lt;Product&gt; 不知道如何处理promoimage,但知道如何处理image。我们还没有发送任何image,所以我们必须解决这个问题。我们可以通过修改 product 使其呈现image || promoimage 来做到这一点,或者将我们的解析更改为:

    const productList = products.map((product, i) => {
      const uniqueItems = []
    
      if (uniqueItems.indexOf(product.promoimage) === -1) {
        uniqueItems.push(product.promoimage)
      }
    
      return (
        <Product
          key={i}
          {...product}
          image={product.image || product.promoimage}
        />
      )
    })
    

    【讨论】:

    • 不错,这行得通。我尝试了一些简单的方法来检查 hasOwnProperty,if (product.hasOwnProperty('promoimage')) { return true },并注意到最后一项消失了。不知道为什么。我已经添加了上面的代码。但我理解你的解决方案。谢谢!!
    • 很高兴听到。您也可以接受回复作为解决方案。
    猜你喜欢
    • 2018-07-02
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多