繁体   English   中英

不能在循环外使用变量 react-native

[英]Can't use the variable outside the loop react-native

我有问题,如下图所示

import * as React from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import { getDatabase, ref, child, get } from "firebase/database";
import auth from '../firebase';

const getFirstName = () => {
  const dbRef = ref(getDatabase());

  let firstName;    
  get(child(dbRef, `users/${ auth.currentUser?.uid }`))
  .then((snapshot) => {
    if (snapshot.exists()) {
      firstName = snapshot.val().firstName;
      console.log(firstName) //Thomas
      return firstName
    } 
  })
  .catch(error => alert(error.message));
  console.log(firstName) //undefined
}


const HomeScreen = () => {    
    return (
      <View style={styles.container}>
        <Text> Hello {getFirstName()}! </Text>
      </View>
    );
};

export default HomeScreen;

在评论中,我已经说明了 console.log() 返回的内容。 如您所见,最后 firstName 是未定义的。 为什么会这样,我该如何解决这个问题,以便我可以在 HomeScreen 中使用该变量

提前致谢!

它应该是这样的:

import * as React from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import { getDatabase, ref, child, get } from "firebase/database";
import auth from '../firebase';

const getFirstName = () => {
  const dbRef = ref(getDatabase());

  let firstName;    
  get(child(dbRef, `users/${ auth.currentUser?.uid }`))
  .then((snapshot) => {
    if (snapshot.exists()) {
      firstName = snapshot.val().firstName;
      console.log(firstName) //Thomas
      return firstName;
    } 
  })
  .catch(error => alert(error.message));
  console.log(firstName) //undefined
}


const HomeScreen = () => {
  const [firstName, setFirstName] = useState();

  useEffect(() => {
    const fName = getFirstName();
    setFirstName(fName);
  }, []);
    
    return (
      <View style={styles.container}>
        <Text> Hello {firstName}! </Text>
      </View>
    );
};

export default HomeScreen;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM