【问题标题】:React Native with Expo app not rendering FlatListReact Native 与 Expo 应用程序不呈现 FlatList
【发布时间】:2025-12-21 03:55:12
【问题描述】:

我没有显示任何错误,但是当我的应用程序运行时出现空白页。当开始放置一些我从另一个项目中复制和粘贴的 api 代码时,它开始呈现一个空白页面,它工作得非常完美,但由于某种原因,它拒绝在这里工作这就是我的代码的样子。这是我的 App.js 文件

import React from 'react'
import { StyleSheet, Text, View } from 'react-native'
import Screen from './app/components/Screen'
import ProductScreen from './app/screens/ProductScreen';

export default function App() {

  return (
    <Screen>
      <ProductScreen />
    </Screen>
  )
}

那么这就是产品screen.js

import React, {useState, useEffect} from 'react'
import { FlatList, StyleSheet, ActivityIndicator, Text, View } from 'react-native'
import Card from '../components/Card';

export default function ProductScreen() {
    const [products, setproducts] = useState([]);
    const [loading, setloading] = useState(true);

    const getProducts = async () => {
        try {
            const response = await fetch('https://fakestoreapi.com/products/1');
            const data = await response.json();
            setproducts(data);
        } catch (error) {
            console.log("Something went wrong in your code",error)
        } finally {
            setloading(false);
        }
    }

    useEffect(() => {
        getProducts();
    }, []);

    return (
        <View>
           {loading ? <ActivityIndicator/> : (
               <FlatList
                   data={products}
                   keyExtractor={(id) => id}
                   renderItem={({item}) => (
                       <Card 
                           title={item.title}
                           subtitle={item.description}
                           img={item.image}
                       />
                   )}
               />
           )}
        </View>
    )
}

const styles = StyleSheet.create({})

最后是 card.js 文件

import { Image, StyleSheet, Text, TouchableOpacity, View } from 'react-native'
import AppText from './AppText';

export default function Card({title, subtitle, img}) {
    return (
        <View style={styles.container}>
            <Image source={img} style={styles.image} />
            <View style={styles.cardText}>
                <AppText style={{color: "black"}}>{title}</AppText>
                <AppText style={{color: "#4ecdc4"}}>{subtitle}</AppText>
            </View>
        </View>
    )
}

我哪里出错了?

【问题讨论】:

    标签: reactjs react-native expo react-native-flatlist


    【解决方案1】:

    您的Expo Snack 中有几个问题。首先你的表达:

    {loading && <FlatList />}
    

    是错误的,因为您将其设置为检查 true 的加载,当您在 getProducts 中检索数据后将其设置为 false

    能够再次使用:

    import React, { useState, useEffect } from 'react'
    import { FlatList, StyleSheet, View } from 'react-native'
    import Card from '../components/Card'
    
    export default function ProductScreen() {
      const [products, setProducts] = useState([])
      const [loading, setLoading] = useState(true)
    
      const getProducts = async () => {
        try {
          const response = await fetch('https://fakestoreapi.com/products/5')
          const data = await response.json()
          setProducts([data])
          setLoading(false)
        } catch (error) {
          console.log('Something went wrong in your code', error)
        }
      }
    
      useEffect(() => {
        getProducts()
      }, [])
    
      return (
        <View style={styles.container}>
          {!loading && products.length !== 0 && (
            <View>
              <FlatList
                data={products}
                keyExtractor={(_, id) => id.toString()}
                renderItem={({ item }) => <Card title={item.title} subtitle={item.description} img={item.image} />}
              />
            </View>
          )}
        </View>
      )
    }
    
    const styles = StyleSheet.create({
      container: {
        backgroundColor: 'lightgrey',
        flex: 1,
      },
    })
    

    Card 对于Image 存在另一个错误。每个内存在传递图像 URL 时应该使用 URI 进行设置:

    <Image source={{ uri: img }} style={styles.image} />
    

    您将面临的另一个问题是在ProductScreen 中,containerView 样式应该应用flex: 1,如上面的代码所示。

    【讨论】:

    • 我删除了 finally 并像你一样设置了 setloading(false) ,它仍然做同样的事情。当我安慰时。记录它返回从 api 请求的项目的数据。
    • 在我的手机上给我一分钟,我会用世博小吃来测试
    • @DARTHVADER 确定
    • 我刚刚在世博会小吃上尝试了您所做的所有编辑,但仍然是空白页面,我不知道您是如何渲染出任何东西的。当你把这些东西渲染出来时,页面样式了吗?比如颜色、边框、间距等?这是我的博览会,您的编辑snack.expo.dev/@vuyi/spontaneous-candy哦,感谢您抽出时间提供帮助。非常感谢。
    • 我从 expo init 在本地运行它。只是学习 React Native,但让我研究一下。我认为这与FlatList 以及如何引入数据有关。
    【解决方案2】:

    查看snack.expo.dev/@vuyi/spontaneous-candy 的代码,您似乎在返回 ProductScreen 时缺少条件渲染。

    您的代码如下所示:

    <View style={styles.container}>
               {loading &&
                   <FlatList
                       data={[products]}
                       keyExtractor={(_, id) => id.toString()}
                       renderItem={({item}) => 
                           <Card 
                               title={item.title}
                               subtitle={item.description}
                               img={item.image}
                           />
                       }
                   />
               }
            </View>

    当它需要看起来像这样时:

     <View style={styles.container}>
               {loading ? null :
                   <FlatList
                       data={[products]}
                       keyExtractor={(_, id) => id.toString()}
                       renderItem={({item}) => 
                           <Card 
                               title={item.title}
                               subtitle={item.description}
                               img={item.image}
                           />
                       }
                   />
               }
            </View>

    添加该条件将阻止您的 Flatlist 组件在访问您正在获取的数据之前进行渲染。看起来您在原始帖子中正确使用了它,但在 Expo Snack 环境中却没有。

    【讨论】:

    • 非常感谢兄弟的帮助我现在看到错误再次感谢非常感谢。
    最近更新 更多