React Native SectionList加载Firebase数据报错无法读取undefined的length
问题原因&修复方案
你的报错是React Native的SectionList组件必填字段缺失导致的,共4处错误需要修改:
- SectionList的sections数据格式不符合要求
SectionList规定每个分组对象必须包含data字段存储当前分组的子项列表,你返回的Firebase数据里子项数组叫iqtiboslar,没有data字段,所以组件读取section.data.length的时候就会抛出undefined的报错。 - Firebase数据处理逻辑错误
你用map遍历文档的时候每次都调用setQuote,会导致前面的文档数据被覆盖,最终quote变量只会存储最后一个文档的内容,不是你要的包含两个对象的数组。 - 组件传参不匹配
你写的Item组件声明接收iqtiboslar参数,但你在renderItem里传的是title,参数对应不上。 - 状态初始化不规范
useState没有给初始值,清理函数直接setQuote()会把状态设为undefined,也有概率引发报错。
修正后的完整代码
import { useState, useEffect } from 'react'; import { View, Text, SectionList, ActivityIndicator, StyleSheet } from 'react-native'; import firestore from '@react-native-firebase/firestore'; // 调整Item组件接收参数和渲染逻辑 const Item = ({ content }) => ( <View> <Text>{content}</Text> </View> ); const HomeScreen = ({ navigation }) => { // 给状态设置初始空数组 const [quote, setQuote] = useState([]); // 新增加载状态避免边界报错 const [loading, setLoading] = useState(true); useEffect(() => { fetchQuotes(); return () => { setQuote([]); }; }, []); const fetchQuotes = async () => { try { const quoteCollection = await firestore().collection('iqtiboslar').get(); // 一次性处理所有文档,映射成符合SectionList要求的格式 const sectionData = quoteCollection.docs.map(doc => { const docData = doc.data().items; // 给每个分组加必填的data字段,对应你原来的iqtiboslar数组 return { ...docData, data: docData.iqtiboslar } }); setQuote(sectionData); } catch (error) { console.log(error); } finally { setLoading(false); } }; return ( <View style={styles.container}> {loading ? ( <ActivityIndicator /> ) : ( <SectionList sections={quote} keyExtractor={(item, index) => item + index} // renderItem的item就是iqtiboslar里的每一项 renderItem={({ item }) => <Item content={item} />} renderSectionHeader={({ section }) => <Text>{section.title}</Text>} /> )} </View> ); }; export default HomeScreen; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, text: { color: 'red', }, });
内容的提问来源于stack exchange,提问作者Dilshod Sh
相关产品推荐
相关产品推荐

