You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React渲染卡片图片时async/await调用返回[object Promise]问题求助

问题原因

async 函数本质上返回的是 Promise 对象,你在 render 里直接调用 this.getImage(d.id),React 会把这个 Promise 直接转成字符串,所以 img 的 src 属性就变成了 "[object Promise]"。控制台能打印正确数据是因为你用了 await/then 处理了 Promise,但渲染阶段并没有等待 Promise 完成。

解决方案

核心是提前把图片URL和卡片数据整合好存入state,不要在渲染时调用异步函数。具体步骤如下:

1. 调整state结构

新增一个对象存储id到图片URL的映射,同时可选添加加载状态:

constructor(props) {
  super(props);
  this.state = {
    data: [],
    imageUrls: {}, // key是卡片id,value是图片URL
    isLoading: true
  };
}

2. 批量请求图片URL

在获取卡片数据后,一次性请求所有图片URL,并存入state:

componentDidMount() {
  // 先获取卡片列表数据(替换成你的卡片API地址)
  fetch('你的卡片数据API')
    .then(res => res.json())
    .then(cardData => {
      this.setState({ data: cardData });
      // 生成所有图片请求的Promise数组
      const imageRequests = cardData.map(item => 
        fetch(`https://api.thedogapi.com/v1/images/search?breed_id=${item.id}`, {
          mode: 'cors',
          headers: { 'x-api-key': 'XXXXXXXXXXXXXXX' }
        })
        .then(r => r.json())
        .then(d => ({ id: item.id, url: d[0].url }))
      );
      // 等待所有请求完成,整理成id-url映射
      Promise.all(imageRequests)
        .then(imageData => {
          const urlMap = {};
          imageData.forEach(item => urlMap[item.id] = item.url);
          this.setState({ imageUrls: urlMap, isLoading: false });
        })
        .catch(err => console.error('图片请求失败:', err));
    })
    .catch(err => console.error('卡片数据请求失败:', err));
}

3. 修改渲染逻辑

直接从state里取对应的图片URL,同时添加加载状态和默认图片:

render() {
  if (this.state.isLoading) {
    return <div>加载中...</div>;
  }
  return (
    <Row>
      {this.state.data.map(d => (
        <Col key={d.id}>
          <Card style={{width: '10rem'}}>
            <Card.Img 
              variant="top" 
              src={this.state.imageUrls[d.id] || 'https://via.placeholder.com/150'} 
            />
            <Card.Body>
              <Card.Title>{d.name}</Card.Title>
              <Card.Subtitle>ID : {d.id}</Card.Subtitle>
              <Card.Text>{d.origin}</Card.Text>
            </Card.Body>
          </Card>
        </Col>
      ))}
    </Row>
  );
}

注意事项

  • 必须给列表项加key属性(用卡片id即可),避免React警告
  • 添加加载状态提升用户体验,防止出现空白页面
  • 设置默认图片地址,避免单个图片请求失败时显示异常
  • 如果卡片数据动态更新(如搜索、分页),要在数据变化时重新请求对应图片URL

内容的提问来源于stack exchange,提问作者SamPhoenix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 18:09:20