在文本元素中反应本机调用函数 [英] React native call function in text element

查看:48
本文介绍了在文本元素中反应本机调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i want to call a getName function which takes a game.set(Integer) and returns a String. This string i want to set inside the text element. The function is working perfectly, I printed the results before returning. Now, after importing the function import { getName } from '../SetsAPI';, the result I get after calling the function is always 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!");
      }
  })
  }

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

Why does this happen? And how can I prevent it? Thank you!

推荐答案

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

You'll want to use useState to store the value, which then causes it to be updated in the UI.

首先在以下位置声明状态:

First declare the state at:

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

这允许我们获取name并调用setName,并给它一个初始值''.

This allows us to get name and call setName, and gives it an initial value of ''.

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

Then in your componentDidMount or in a useEffect hook, you'll do:

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 属性.

This causes your component to rerender itself, and then you can use the name property in your render method.

另见:

这篇关于在文本元素中反应本机调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆