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

React从自建API加载图片失败怎么办?姓名字段可正常显示

问题描述

从自建API获取用户数据时,first_name和last_name能正常渲染,但图片无法加载,仅显示alt文本。已尝试通过this.state.image关联API返回的url_img字段,但未生效。

相关代码如下:

class LastUserInDb extends Component {
  constructor(props) {
    super(props);
    this.state = {
      usuario: [],
    };
  }

  componentDidMount() {
    fetch("http://localhost:3050/usersRoutes/lastUser")
      .then((response) => response.json())
      .then((usuario) => {
        console.log(usuario)
        this.setState({
          apellido: usuario.data.last_name,
          nombre: usuario.data.first_name,
          image: usuario.data.url_img
          
        });
      });
      console.log(this.state.image)
  }

render() {
  return (
    <div className="col-lg-6 mb-4">
      <div className="card shadow mb-4">
        <div className="card-header py-3">
          <h5 className="m-0 font-weight-bold text-gray-800">
            Ultimo usuario creado:<tr></tr>
          {this.state.apellido}, 
          {this.state.nombre}
          </h5>
        </div>
        <div className="card-body">
        
          <div className="text-center">
            
          <img 
          className="img-fluid px-3 px-sm-4 mt-3 mb-4"
          style={{ width: "40rem" }}
          src={"http://localhost:3000" + this.state.image} 
          alt= "foto ultimo usuario"
            />
         
           
          </div>
          <p>
      
          
          </p>
          
        </div>
      </div>
    </div>
  );
}
}

export default LastUserInDb;

API返回数据:

{
  "data": {
    "url_img": "/images/users/1670121813886dennis buzenitz.jpg",
    "idUsuario": 29,
    "first_name": "Dennis",
    "last_name": "Buzenitz",
    "email": "dbuzenitz@gmail.com",
    "password": "$2a$10$rdmiLSvCRpuNVlBdU0daLOyVWAaizxpJAO/9Sd0lArdFP1kjfi666",
    "image": "1670121813886dennis buzenitz.jpg"
  }
}
解决方案

1. 修正图片路径的域名/端口

当前代码拼接的是前端项目的localhost:3000,但如果图片实际存储在后端服务器(localhost:3050),需要将src改为后端地址:

src={"http://localhost:3050" + this.state.image}

如果图片确实在前端项目中,要确保图片文件存在于前端项目的public/images/users目录下(React默认从public目录加载静态资源)。

2. 验证后端静态资源配置

若图片在后端,需确保后端已配置静态资源托管。以Express为例,需添加以下代码来托管images目录:

app.use('/images', express.static(path.join(__dirname, 'images')));

3. 调试路径有效性

在浏览器控制台查看img标签的src属性,复制该地址直接在浏览器地址栏访问:

  • 若无法打开,说明路径错误,检查域名、端口或文件路径是否匹配;
  • 若能打开,检查是否存在跨域问题(后端需配置CORS允许前端访问)。

4. 规范初始State(可选)

在constructor中初始化所需字段,避免渲染时出现undefined警告:

constructor(props) {
  super(props);
  this.state = {
    apellido: '',
    nombre: '',
    image: ''
  };
}

5. 修正异步日志位置

componentDidMount中的console.log(this.state.image)写在fetch外部,会在异步请求完成前执行,因此输出undefined。若要查看更新后的state,需将日志移至setState的回调中:

this.setState({
  apellido: usuario.data.last_name,
  nombre: usuario.data.first_name,
  image: usuario.data.url_img
}, () => {
  console.log(this.state.image); // 此时能拿到更新后的image值
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 20:10:25