首页 > 解决方案 > React Native - 在平面列表中显示承诺的图像

问题描述

我目前有多个类别,每个类别都有一个包含图像名称的数组。这些数组是从 JSON 文件中获取的,我希望使用 flatList 来显示它们。但是,当我进行以下尝试时,它说无法读取未定义的属性 '0' ...

export default function display() {

const [all, setAll] = useState([])

const fetching = async() => {

     ... //code that fetches the JSON file

     setImages([{title: "A", arr: arrA},
                    {title: "B", arr: arrB},
                    {title: "C", arr: arrC}]
}

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

...

    const display = ({arr}) => ... //function that displays the pictures
 

    const Item = ({title, arr}) => {
        return(
        <View style={styles.categoryContainer}>
            
            {display(arr)}
            <Text style={styles.tags}>{title}</Text>

        </View>
        )
    }

    const renderItem = (item) => {
        return(
            <Item title={item.title}
                arr={item.arr}/>
        ) 
    }

    return (
        <View> 
            {console.log(all)}
            <FlatList
             data={all}
             renderItem={renderItem}
             keyExtractor={item => item.title}/>
        </View>
    )
}

return 语句中的 console.log 显示: console.log(all)

我的代码的哪一部分是错误的?任何帮助将不胜感激!

标签: reactjsreact-nativefetchreact-native-flatlist

解决方案


添加一个加载器,在获取图像时将其设置为 true,在获取图像的调用完成后将其设置为 false。

const [all, setAll] = useState([]);
const [isLoading, setLoader] = useState(true);

const fetching = async() => {

 ... //code that fetches the JSON file
 setLoader(false);
 setImages([{title: "A", arr: arrA},
                {title: "B", arr: arrB},
                {title: "C", arr: arrC}]
 }

然后在你的渲染中检查加载器是否为假

return (
    <View> 
        { isLoading 
         ? <Text>Loading...</Text> 

         : <FlatList
            data={all}
            renderItem={renderItem}
            keyExtractor={item => item.title}/>
         }
    </View>
)

推荐阅读