【问题标题】:Rendering Firebase data in map function在地图功能中渲染 Firebase 数据
【发布时间】:2021-06-11 20:29:13
【问题描述】:

我正在尝试从 firebase get 函数渲染数据,但它没有显示任何内容。图像 console.log 显示 2 个值,但不会在页面上呈现。有没有人建议为什么会这样。

  function cards(){
     store.collection('users').get().then(snapshot => {
      images = snapshot.docs.map(doc => doc.data().image)
      console.log(images)
       return images.map((doc) => {
        return (
          <Card style={[styles.card, styles.card1]}>
            <Text style={styles.label}>A</Text>
          </Card>
        )
      })
    })
  }

  return (
    <View>
     <View style={styles.viewport}>
      <CardStack style={styles.content}>
      {cards()}
      </CardStack>
     </View>
    </View>
  )
}

【问题讨论】:

    标签: javascript arrays firebase google-cloud-firestore


    【解决方案1】:

    您正在尝试调用异步函数并使用 then 从中获取返回。你总是会从中得到一个 undefined ,因为 then 在你的函数已经返回 undefined 或者在这种情况下什么都没有返回时完成。

    尝试使用状态并正确处理异步调用,如下所示:

    import React, { useState, useEffect } from "react";
    
    const YourComponent = () => {
      const [list, setLits] = useState([]);
    
      useEffect(() => {
        const snapshot = await store.collection("users").get();
        const images = [];
        snapshot.docs.forEach((s) => {
          images.push(doc.data().image);
        });
    
        setLits(images);
      }, []);
    
      return (
        <View>
          <View style={styles.viewport}>
            <CardStack style={styles.content}>
              {list.map((i) => {
                return (
                  <Card style={[styles.card, styles.card1]}>
                    <Text style={styles.label}>A</Text>
                  </Card>
                );
              })}
            </CardStack>
          </View>
        </View>
      );
    };
    
    

    【讨论】:

    • 卡片功能没有运行
    • 为了帮助澄清:视图内的函数需要是同步的 - useEffect 和 useState 适应异步 firestore 调用。
    猜你喜欢
    • 2019-01-31
    • 1970-01-01
    • 2021-05-25
    • 2020-10-12
    • 2020-09-18
    • 2019-02-07
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    相关资源
    最近更新 更多