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

React Native从API获取数据后图片无法加载问题求助

解决React Native中JsonPlaceHolder图片无法加载的问题

嘿,别着急!我看了你的代码,咱们一步步排查问题:

首先,几个关键问题点:

  1. 废弃的生命周期方法:你用了componentWillMount,这个方法在React Native新版本里已经被标记为废弃,推荐用componentDidMount来发起网络请求,它是组件挂载后执行的正确时机。
  2. 初始状态与条件渲染:你的photos初始值是空字符串,组件第一次渲染时,Image会尝试加载空的uri,这可能导致渲染异常。咱们可以改成null,并添加条件渲染确保只有拿到有效URL后再渲染图片。
  3. 图片尺寸合理性:你设置的600x600尺寸可能超出了设备屏幕范围,导致图片显示不全或者不被渲染,建议先调整为更适中的尺寸测试。

修改后的代码示例:

import React, { Component } from 'react';
import { Image, StyleSheet, Text, View } from 'react-native';

export default class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      photos: null, // 初始设为null,避免空字符串导致的问题
      titles: ''
    };
  }

  // 替换为componentDidMount,发起网络请求的正确生命周期
  componentDidMount(){
    this.fetchData();
  }

  fetchData = async () => {
    try {
      // 直接用HTTPS请求原API,避免手动替换的步骤
      let response = await fetch('https://jsonplaceholder.typicode.com/photos/1');
      let json = await response.json();
      // 原返回的url是http,但placehold.it支持HTTPS,直接使用也可以,替换也没问题
      this.setState({titles: json.title, photos: json.url.replace('http','https')});
    } catch (error) {
      console.error('请求出错:', error); // 添加错误捕获,方便排查请求问题
    }
  };

  render() {
    console.log('当前图片URL:', this.state.photos);
    return (
      <View style={styles.container}>
        {/* 条件渲染:只有photos存在时才渲染图片,避免初始空值导致的异常 */}
        {this.state.photos && (
          <Image 
            source={{uri: this.state.photos}} 
            style={{height: 300, width: 300}} // 调整为适中尺寸,适配大多数设备
            resizeMode='cover' 
          />
        )}
        <Text> Title: {this.state.titles} </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
  }
});

额外排查步骤(针对Android设备):

如果修改后还是无法加载,可能是Android的网络安全策略限制:

  • 在android/app/src/main/res/xml目录下创建network_security_config.xml文件,内容如下:
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">jsonplaceholder.typicode.com</domain>
        <domain includeSubdomains="true">placehold.it</domain>
    </domain-config>
</network-security-config>
  • 然后在android/app/src/main/AndroidManifest.xml的application标签中添加:
android:networkSecurityConfig="@xml/network_security_config"

最后验证:

先确认console.log输出的图片URL是否正确,复制到浏览器里看看能不能正常打开。如果浏览器能打开,那上面的修改应该能解决问题啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:47:44