React使用map遍历数组渲染组件时props无法正常显示问题求解
React map遍历渲染子组件props不显示问题修复
存在的2处核心错误
- map遍历传递props时,误将整个商品数组
products传给了子组件的prod属性,而非当前遍历到的单个商品对象 - 子组件直接将整个props对象命名为
prod,没有正确获取到props下挂载的prod属性内容
修复代码
export const products = [ { id: 1, title: "Chocotorta", desciption: "Torta de chocolate y dulce de leche", price: "$2,40", imgDesc: "", imgUrl: "" } ]; // 解构props获取传入的prod商品对象 const Item = ({ prod }) => { return ( <> <Card> <CardImg alt={prod.imgDesc} src={prod.imgUrl} top width="100%" /> <CardBody> <CardTitle tag="h5">{prod.title}</CardTitle> <CardSubtitle className="mb-2 text-muted" tag="h6"> {prod.price} </CardSubtitle> <CardText>{prod.desciption}</CardText> <Button>Mostrar detalle</Button> </CardBody> </Card> </> ); }; return ( <> {loading ? ( <div style={spinnerStyle}> <Spinner color="primary" size=""> . </Spinner> </div> ) : ( // 传递当前遍历的单个商品,同时将key挂载到遍历的根组件Item上 products.map((prod) => <Item key={prod.id} prod={prod} />) )} </> );
额外说明
React中遍历渲染列表时,key属性需要挂载到map返回的第一个根元素上,不需要放到子组件内部的Card标签上。
内容的提问来源于stack exchange,提问作者Martin Abel
相关产品推荐
相关产品推荐

