【问题标题】:How to get Firebase Cloud Firestore data in one line that returns one value in React Native如何在 React Native 中返回一个值的一行中获取 Firebase Cloud Firestore 数据
【发布时间】:2020-02-01 20:53:42
【问题描述】:

我正在尝试在 React Native 的 Text 组件中的一行中从 firebase cloud firestore 数据库中获取数据。这是我想要做的:

...
<Text style={styles.name}>
 {firebase.firestore().collection("users").doc(post.uid).get().name}
</Text>
...

此代码试图通过获取 id 为“post.uid”的文档在 React Native Text 组件中放置一个值,以便在调用值“name”的位置返回文档数据并返回单个字符串。我将不胜感激有关如何执行此操作的任何帮助,因为我无法找出解决方案。提前谢谢!

【问题讨论】:

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


    【解决方案1】:

    你可以得到最接近的是使用await

    (await firebase.firestore().collection("users").doc(post.uid).get()).data().name
    

    我建议仔细研究 getting data 上的 Firestore 文档,并首先尝试获取渲染函数之外的值。


    更新

    由于您使用的是 react,我强烈建议您采用这种方法:

    1. 在您的componentDidMount 中开始加载数据。
    2. 加载数据后,调用setState() 将其添加到状态中。

      结合这些看起来像:

      componentDidMount() {
        firebase.firestore().collection("users").doc(post.uid).get().then((doc) => {
          this.setState({ name: doc.data().name });
        }
      }
      
    3. 然后从状态渲染数据。

      <Text style={styles.name}>
       {this.state.name}
      </Text>
      

    另见:

    【讨论】:

    • 我收到一个 TypeError,它不是一个函数,它只能在异步函数中调用。我将如何使用外部函数实现此功能?如果你能帮助我,我将不胜感激!
    • 是的,但我找不到解决方案。
    • 我添加了一个更惯用的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 2021-02-23
    • 2018-12-18
    相关资源
    最近更新 更多