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

如何用React JS从API获取图片?API图片无法显示求助

Fixing Image Display Issues in React When Fetching from an API

Hey there! Let's break down why your images aren't showing up and fix it step by step.

The Core Issue

First off, I spot a key syntax mix-up: you're using source={{uri: ...}} for your <img> tag—that's React Native syntax, not for web-based React! On the web, standard HTML <img> elements rely on the src attribute to load images. That's almost certainly the main reason your images aren't rendering.

Corrected Code

Here's how to adjust your component code to work for web React:

// Inside your component's render/return logic
this.state.filteredData.map((data, i) => (
  <div key={i}> {/* Always add a unique key prop for list items in React! */}
    <span>{data.details.name}</span> <br/>
    <img 
      src={data.details.image} 
      style={aStyle} 
      alt={data.details.name} {/* Include alt text for accessibility and broken image fallback */}
    /> <br/>
    <span>{data.details['section of law']}</span> <br />
    <span>{data.details['type of person']}</span>
  </div>
))

// Your style stays the same
const aStyle = { width: 300, height: 360 };

Additional Troubleshooting Checks

If the image still doesn't load after fixing the src attribute, run through these common issues:

  • Validate the image URL: Copy the value of data.details.image directly into your browser's address bar. If it doesn't load a valid image, the API might be returning an invalid, expired, or broken URL.
  • Check for CORS errors: Open your browser's DevTools (Network tab) to see if there's a cross-origin resource sharing (CORS) error. Some APIs block requests from external web apps—you might need a proxy server or to confirm the API allows your app's domain.
  • Rule out style conflicts: Temporarily add a border to your aStyle (like border: '1px solid red') to confirm the image element is actually being rendered on the page. Sometimes styles can accidentally hide elements.
  • Handle missing image values: Make sure data.details.image isn't null or undefined before rendering. Add a conditional fallback to avoid broken image icons:
    {data.details.image ? (
      <img src={data.details.image} style={aStyle} alt={data.details.name} />
    ) : (
      <span>No image available</span>
    )}
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:13:53