Rails API上传图片到Cloudinary后React端无法遍历展示各商品对应图片
问题修复方案
1. 后端可选优化(非必须,可简化前端处理逻辑)
你可以直接在后端序列化时返回图片对应的Cloudinary资源标识,避免前端多层级取字段:
def index @items = Item.all render json: @items.map { |item| item.as_json.merge( item_photo_key: item.itemPhoto.attached? ? item.itemPhoto.blob.key : nil ) } end
不改原有控制器逻辑也可以正常适配,用你当前返回的嵌套结构即可。
2. 前端代码修改
修改itemList.js如下,核心修复重名、动态生成图片地址、类型错误等问题:
import { Card } from 'react-bootstrap'; import PropTypes from 'prop-types'; import { Cloudinary } from '@cloudinary/url-gen'; const ItemList = ({ items }) => { const cld = new Cloudinary({ cloud: { cloudName: '替换为你自己的Cloudinary cloudName', }, url: { secure: true, }, }); return ( <div className="container-fluid flex-column justify-content-center"> {items.map((item) => ( <Card key={item.id}> <table className="m-3 col-10"> <tbody className="col-12"> <tr className="m-3"> <div className="m-3 col-12 flex-container justify-content-center"> <div className="col-12 d-flex justify-content-center"> <div className="col-12 d-flex justify-content-center"> <p className="col-8 d-flex justify-content-center serviceCategoryTitle p-2">{item.id}</p> <p className="col-8 d-flex justify-content-center serviceCategoryTitle p-2">{item.itemName}</p> <p className="col-8 d-flex justify-content-center serviceCategoryTitle p-2">{item.itemDescription}</p> <p className="col-8 d-flex justify-content-center serviceCategoryTitle p-2">{item.itemPrice}</p> {/* 动态生成当前商品的图片地址,增加无图兼容判断 */} {item.itemPhoto?.blob?.key && ( <img src={cld.image(item.itemPhoto.blob.key).toURL()} alt={`${item.itemName}展示图`} /> )} </div> </div> </div> </tr> </tbody> <hr className="col-12" /> </table> </Card> ))} </div> ); }; ItemList.propTypes = { // 修正类型错误,商品是对象数组而非数组的数组 items: PropTypes.arrayOf(PropTypes.object).isRequired, }; export default ItemList;
注意事项
如果前端获取不到item.itemPhoto.blob.key,可以在遍历逻辑中打印item查看接口返回的实际字段结构,部分ActiveStorage版本序列化后字段可能为蛇形命名item_photo,对应调整字段名即可。
内容的提问来源于stack exchange,提问作者Railon Acosta
相关产品推荐
相关产品推荐

