平面列表未渲染

问题描述 投票:0回答:1

即使我在控制台上记录了来自 API 的数据,我的 FlatList 也不会呈现。这是我的代码:

import { FlatList, Image, StyleSheet, Text, View } from 'react-native'
import GlobalApi from '../Utils/GlobalApi';
import React, { useEffect, useState } from 'react'

const CategoryList = () => {
  const getCategory =()=>{
    GlobalApi.getCategory().then(resp => {
      console.log(resp.categories);
      setCategories(resp.categories)
    })
  }
  const [categories, setCategories] = useState();
  return (
    <View>
      <FlatList
        data={categories}
        horizontal={true}
        keyExtractor={item => item.id}
        renderItem={({item,index}) => (
          <View>
            <Image source={{uri:item?.icon?.url}} 
              style={{width:40, height: 40}}
            />
            <Text>{item.id}</Text>
          </View>
  )}      
      />
    </View>
  )
}

export default CategoryList

const styles = StyleSheet.create({})
javascript reactjs react-native
1个回答
0
投票

您应该将类别初始化为空数组以避免任何 FlatList 尝试渲染时的潜在问题。另外,使 确保您的 FlatList 被赋予有效的样式或 View

下面是代码,我也添加了图标的虚拟数据 图标在平面列表中工作

const CategoryList = () => {   const [categories, setCategories] =
 useState([]);
 
  const getCategory = () => {
     GlobalApi.getCategory().then(resp => {
       console.log(resp.categories);
      setCategories(resp.categories);
     }).catch(err => {
      console.error(err);
    });   }; 
   useEffect(() => {
     const dummyData = [
      { id: '1', icon: { url: 'https://via.placeholder.com/40' } },
      { id: '2', icon: { url: 'https://via.placeholder.com/40' } },
      { id: '3', icon: { url: 'https://via.placeholder.com/40' } },
    ];
   setCategories(dummyData);   }, []);

下面是用户界面代码,我也与您分享了世博会小吃链接 可以修改那里的代码

 <View style={styles.container}>
      <FlatList
        data={categories}
        horizontal={true}
        keyExtractor={item => item.id}
        renderItem={({ item }) => (
          <View style={styles.itemContainer}>
            <Image 
              source={{ uri: item?.icon?.url }} 
              style={styles.image} 
            />
            <Text>{item.id}</Text>
          </View>
        )}
      />
    </View>

展会链接

© www.soinside.com 2019 - 2024. All rights reserved.