【问题标题】:How to loop through firestore array and fetch values in React Native如何在 React Native 中循环遍历 firestore 数组并获取值
【发布时间】:2021-09-21 05:23:14
【问题描述】:

我的 firestore 数据库中有一个包含服务类别的数组。当用户进入详细信息部分时,我想显示这些类别。

我的问题是,每当我输入详细信息屏幕时,我在尝试映射数组时都会遇到错误。

我在这里遇到错误:

{details.category.map((category,index)=> (
            <View style={styles.categoryContainer} key={index}>
                <FontAwesome name="tag" size={16} color="#fff" />
                <Text style={styles.category}>{category}</Text>
              </View>
           ))} 

"Render Error: undefined is not an object, evaluating details.category.map"

即使我删除了这行代码,我也会得到所有正确的细节。我做错了什么?

这是我的代码:

const DetailsScreen = ({route}) => {

  const [details, setDetails] = useState([]); 
  const servID = route.params.serviceID;
  const navTitleView = useRef(null);

  const fetchServicesDetails = async () => {
    try{

     firestore()
      .collection("Services")
      .doc(servID)
      .get() 
      .then((snapshot) => { 
        if (snapshot.exists) { 
          setDetails(snapshot.data()); 
          } else { 
              console.log("doesn't exist");
           } 
        })
    
    }catch(e){
      console.log(e)
    }
  }

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

    

  return (
    <View style={styles.container}>

        <View style={styles.section}>
          <View style={styles.categories}>
           {details.category.map((category,index)=> (
            <View style={styles.categoryContainer} key={index}>
                <FontAwesome name="tag" size={16} color="#fff" />
                <Text style={styles.category}>{category}</Text>
              </View>
           ))}     
            
          </View>
        </View>

        
  
  );
};

export default DetailsScreen;

【问题讨论】:

    标签: reactjs firebase react-native google-cloud-firestore


    【解决方案1】:

    问题是您的初始状态为空数组[],而您正尝试访问未定义的details.category 等数组上的属性“类别”(它不是地图)。

    snapshot.data() 对象包含整个文档的数据。这是一张地图,而不是一个数组。您应该在您的州设置类别数组。

    const [categories, setCategories] = useState([])
    
    //after fetching the data
    setCategories(snapshot.data().category)
    
    // Then use a map on this categories object
    categories.map((categories, index) => {...})
    

    如果您希望详细信息状态保持原样,请将您的初始状态设置为这样的地图:

    const [details, setDetails] = useState({category: []})
    // now details.category is defined
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 2017-08-22
      • 2021-09-29
      • 1970-01-01
      • 2014-07-12
      • 1970-01-01
      相关资源
      最近更新 更多