reactjs - 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)
我的代码的哪一部分是错误的?任何帮助将不胜感激!
解决方案
添加一个加载器,在获取图像时将其设置为 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>
)
推荐阅读
- actions-on-google - 琐事游戏不可用。请稍后再试
- c# - 无法加载文件或程序集 'System.Net.Http, Version=4.2.0.0 系统找不到指定的文件
- java - 从字符串数组中获取值,其中每个字符串都包含一个值 获取值
- angular - Angular - 我无法在我的页面上显示数据
- angular - 在以角度 6 将视频文件上传到服务器之前压缩视频文件
- javascript - 选择下拉值更改时如何调用javascript函数?
- google-sheets - 空白单元格为零(数据透视表)
- youtube-api - 在 YouTube 数据 API V3 上列出 YouTube 订阅者错误?
- php - 如何修复此错误“Eloquent 构建器实例上不存在属性 [折扣]。”
- javascript - 如何将数组推入嵌套数组?