【问题标题】:React native call function in text element在文本元素中反应本机调用函数
【发布时间】:2021-05-12 21:47:13
【问题描述】:

我想调用一个getName 函数,它接受game.set(Integer)returns a String。 我想在文本元素中设置这个字符串。 该功能运行良好,我在返回之前打印了结果。 现在,导入函数import { getName } from '../SetsAPI';后,调用函数得到的结果总是undefined

函数调用:

import { getName } from '../SetsAPI';
...
    <View style={styles.row}>
      <Text style={styles.text}>Game: </Text>
          <View style={styles.questionAmount}>
               <Text>{getName(game.set)}</Text>
          </View>
     </View>

功能:

 export const getName = (setId)=>{
    console.log("setId: " + setId)
    setsRef
    .doc(setId)
    .get()
    .then((doc) => {
      if (doc.exists) {
        console.log("document name: " + doc.data().name)
        return doc.data().name;
      } else {
        console.log("No such document!");
      }
  })
  }

为什么会这样?我该如何预防呢? 谢谢!

【问题讨论】:

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


    【解决方案1】:

    您需要使用 useState 来存储值,然后在 UI 中更新它。

    首先声明状态:

    {name, setName} = useState('');
    

    这使我们可以获取name 并调用setName,并为其赋予初始值''

    然后在您的componentDidMountuseEffect 挂钩中,您将执行以下操作:

    setsRef
    .doc(setId)
    .get()
    .then((doc) => {
      if (doc.exists) {
        console.log("document name: " + doc.data().name)
        setName(doc.data().name);
      } else {
        console.log("No such document!");
      }
    

    这会导致您的组件重新渲染自己,然后您可以在渲染方法中使用name 属性。

    另见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      • 2020-05-28
      • 2016-09-12
      • 1970-01-01
      • 2023-03-11
      • 2019-09-05
      相关资源
      最近更新 更多