【问题标题】:API images do not load in react nativeAPI 图像不会在本机反应中加载
【发布时间】:2020-07-17 02:09:31
【问题描述】:

我在尝试加载来自我的 API(连同其他数据)的图像时遇到问题,但它没有出现在手机/模拟器上,也没有加载。

import React, { useState, useEffect } from 'react';
import { View, Text, Image, StyleSheet, FlatList, TouchableOpacity } from 'react-native';

import api from '../services/api';

export default function SpotList({ tech }) {
  const [spots, setSpots] = useState([]);

  useEffect(() => {
    async function loadSpots() {
      const response = await api.get('/spots', { // /spots?tech=tecnologia
        params: { tech }
      })

      setSpots(response.data);
      console.log(spots)
    }

    loadSpots();
  }, []);

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Empresas que usam <Text style={styles.bold}>{tech}</Text></Text>

      <FlatList 
        style={styles.list}
        data={spots}
        keyExtractor={spot => spot._id}
        horizontal
        showsHorizontalScrollIndicator={false} //barra de rolagem
        renderItem={({ item }) => (
          <View style={styles.listItem}>
            <Image style={styles.thumbnail} source={{ uri: item.thumbnail_url }}/>
            <Text style={styles.company}>{item.company}</Text>
            <Text style={styles.price}>{item.price ? `R$${item.price}/dia` : 'GRATUITO'}</Text>
            <TouchableOpacity onPress={() => {}} style={styles.button}>
              <Text style={styles.buttonText}>Solicitar Reserva</Text>
            </TouchableOpacity>
          </View>
        )}
      />
    </View>
  );
}

当我运行console.log(spots)命令时,终端正常返回URL给我。

[
  {
    "techs": [
      "ReactJS",
      "Node.js"
    ],
    "_id": "5f10b8e8ed571238cc9434ad",
    "user": "5f10b3afed571238cc9434ab",
    "thumbnail": "google-1594931431941.jpg",
    "company": "Google",
    "price": 68,
    "__v": 0,
    "thumbnail_url": "http://localhost:3333/files/google-1594931431941.jpg",
    "id": "5f10b8e8ed571238cc9434ad"
  }
]

当我通过浏览器打开 thumbnail_url 时,它会正常显示图像。

【问题讨论】:

  • 尝试使用 IP 地址而不是 'localhost'
  • 这发生在 android9 (PIE) 或更高版本上,您需要确保所有 URL 都是 https,而不是 http
  • 问题出在API上,数据正常到达,但是图片没有显示在屏幕上

标签: javascript reactjs image react-native express


【解决方案1】:

React Native 中的网络图像需要高度和宽度才能显示。您可以将它们添加为单独的道具,也可以将它们作为样式传递。

【讨论】:

  • 我正在传递高度和宽度,仍然没有显示
【解决方案2】:

尝试在样式中添加这个 缩略图:{ 宽度:50, 身高:50, }

你可以在这里找到更多相关信息:https://reactnative.dev/docs/image

【讨论】:

  • 我正在浏览下面的样式,但我现在尝试直接去,它也不起作用,图像不显示
猜你喜欢
  • 2022-12-05
  • 2022-07-24
  • 1970-01-01
  • 2021-12-10
  • 2021-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-11
相关资源
最近更新 更多