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

Strapi结合React开发无法正常获取显示上传图片

React + Strapi v4 上传图片无法显示修复方案

你的代码有3处核心错误,改完就能正常读取图片字段、显示图片:

1. 字段路径写错了

Strapi v4 所有媒体、关联类型的字段,返回结构都在attributes下多嵌了一层data,你写的animal.attributes.image.url路径不对,正确的图片地址路径是animal.attributes.image.data.attributes.url。开发时可以在接口请求的.then里打个console.log打印返回值,一眼就能看到结构层级。

2. 图片地址没拼服务端域名

Strapi 上传模块返回的图片url是相对路径,比如/uploads/cat_1234.jpg,直接把这个值塞给img的src,浏览器会默认去你前端运行的域名(比如localhost:3000)下找资源,肯定报404。你代码里定义了api_url但是没用到,需要把这个服务端地址拼在图片相对路径前面。

3. 列表key写法错误

你现在写的key="animal.attributes.id"是把固定字符串当key,React做列表diff的时候会出异常,要去掉引号,取真实的id值:key={animal.id}。


修复后的完整代码

import { useEffect, useState } from 'react';
import axios from 'axios'


function AnimauxListe() {
    const [error, setError] = useState(null);
    const [Animaux, setAnimaux] = useState([]);
    const api_url = "http://localhost:1337"
 
    useEffect(() => {
        axios
          // 如果populate=*还是拿不到图片,就换成明确指定populate字段的写法
          // .get('http://localhost:1337/api/animaux?populate[image][populate]=*')
          .get('http://localhost:1337/api/animaux?populate=*')
          .then(({ data }) => {
            setAnimaux(data.data)
          })
          .catch((error) => setError(error))
      }, [])
    
      if (error) {
        return <div>请求出错: {error.message}</div>;
      }
  return (
    <div className="App">
        <h2> 数据库内动物列表展示</h2>
    <ul>
    {Animaux.map(animal => {
      // 提前解构字段,加可选链避免字段不存在时页面直接崩溃
      const { nom, Description, image } = animal.attributes
      const imageSrc = image?.data?.attributes?.url 
        ? `${api_url}${image.data.attributes.url}` 
        : ''
      return (
        <div key={animal.id} className="card" >  
          <img 
            src={imageSrc}
            className="card-img-top" 
            alt="动物图片"
          />  
          <div className="card-body">  
            <h5 className="card-title">{nom}</h5>
            <p className="card-text">{Description}</p> 
            <a href="#" className="btn btn-primary">查看{nom}</a> 
          </div> 
        </div>
      )
    })}
    </ul>
  </div>
  )
}

补充说明

  • 如果用populate=*还是拿不到image字段,就换成注释里明确指定populate媒体字段的写法,部分Strapi小版本中,通配符populate不会自动拉取深层的媒体资源
  • 本地开发记得在Strapi后台的CORS配置里,把你前端的运行地址(比如http://localhost:3000)加到允许列表,不然会报跨域错误
  • 部署上线时把api_url换成你Strapi服务的线上域名,不要写死localhost

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 04:57:18