如何用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.imagedirectly 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(likeborder: '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.imageisn'tnullorundefinedbefore 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
相关产品推荐
相关产品推荐

