【问题标题】:How do I map the data from an array inside an JSON file in react js?如何在 React js 中映射 JSON 文件中的数组中的数据?
【发布时间】:2021-05-11 15:43:21
【问题描述】:

这就是我想要展示的内容:

如何从这个 JSON 数据映射“源”数组并显示多行?

{
    "_id": 1,
    "name": "Name",
    "brand": "Brand",
    "image": "/images/image.jpg",
    "sources": [
        {
            "retailer": 1,
            "price": "0.00",
            "retailer_name": "Onbuy",
            "retailer_image": null
        },
        {
            "retailer": 12,
            "price": "0.00",
            "retailer_name": "Curry PC World",
            "retailer_image": "/images/currys1.jpg"
        },
        {
            "retailer": 2,
            "price": "0.00",
            "retailer_name": "AWD-IT",
            "retailer_image": null
        },
        {
            "retailer": 3,
            "price": "0.00",
            "retailer_name": "Scan",
            "retailer_image": null
        }
    ]
}

这是我的代码,用于连续显示每个数据源:

function ProductPage({match,history}) {

    const dispatch = useDispatch()
    const productDetails = useSelector(state => state.productDetails)
    const {error, loading, product} = productDetails
  
    return (<>
            
            {loading ? <h2 className="center-title"><Spinner animation="border" variant="success"/> Loading...</h2>: error ? <h3 className="center-title">{error}</h3> :
                
                <Row className="move-down">
                    <Col md={3}>
                        <ListGroup>
                            <ListGroup.Item ><h3>{product.name}</h3></ListGroup.Item>
                            {/* I Want to map here */}
                            <ListGroup.Item className="d-flex justify-content-between align-items-center ">
                                <Image src={IMAGE GOES HERE}/>
                                <h5 className="text-center">{PRICE GOES HERE}</h5> 
                                <Button variant="success">View</Button>
                            </ListGroup.Item>
                            {/* ------------------------------------------------------------------------- */}
                        </ListGroup>     
            }
                
        </>
    )
}

export default ProductPage

我也在使用redux将payload发送到这个组件

谢谢

编辑问题已修复:我也忘记将源添加到 statestate={product:{sources:[]}}

【问题讨论】:

    标签: javascript arrays json reactjs react-redux


    【解决方案1】:

    你可以像这样使用map

    {product.sources.map((item, index) => (
     <ListGroup.Item key={index} className="d-flex justify-content-between align-items-center ">
       <Image src={item.retailer_image}/>
       <h5 className="text-center">{item.price}</h5> 
       <Button variant="success">View</Button>
     </ListGroup.Item>
    ))}
    

    【讨论】:

      猜你喜欢
      • 2021-01-16
      • 2021-03-25
      • 2020-08-21
      • 2023-01-15
      • 1970-01-01
      • 2021-07-17
      • 2020-10-28
      • 2023-01-02
      • 1970-01-01
      相关资源
      最近更新 更多