【问题标题】:How to render field on firestore db on screen in react native?如何在本机反应中在屏幕上呈现firestore db上的字段?
【发布时间】:2022-11-16 00:51:47
【问题描述】:

基本问题,但我一直在努力。

const GetDisplayName = async () => {
    const docRef = doc(db, "userInfo", user.uid);
    const docSnap = await getDoc(docRef);

    if (docSnap.exists()) {
      console.log(docSnap.get("fullname"));
      const res = docSnap.get("fullname");
      return <Text>{res}</Text>;
    } else {
      return <Text>hello</Text>;
    }
  };

无论我尝试什么,我都无法让 GetDisplayName 呈现。我什至尝试将 res 变量更改为纯字符串。我不断收到无效的对象作为反应子错误。

我的返回函数看起来像这样。如果两个都返回 JSX,为什么我的 Test 组件可以正常工作,但我的 GetDisplayName 组件不能正常工作?

const Test = () => <Text>"yooo</Text>;
  //const docRef = doc(db, "userInfo", userID);
  

  return (
    <View>
      <Text>Welcome Home!</Text>
      <Test />
      <GetDisplayName />

【问题讨论】:

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


    【解决方案1】:

    由于涉及async/await,“GetDisplayName”的返回类型是 Promise 元素,而不是 JSX 元素。因此,您会看到 objects are not valid as react child 错误。你必须做这样的事情来显示结果 -

    const GetDisplayName = () => {
      const [name, setName] = useState('');
    
      useEffect(() => {
        const getName = async () => {
          const docRef = doc(db, "userInfo", user.uid);
          const docSnap = await getDoc(docRef);
          if (docSnap.exists()) {
            console.log(docSnap.get("fullname"));
            const res = docSnap.get("fullname");
            setName(res);
          }
        };
        getName();
      }, []);
    
      return <Text>{name}</Text>;
    };
    

    【讨论】:

      猜你喜欢
      • 2021-12-13
      • 2020-05-12
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 2014-10-07
      • 1970-01-01
      • 2019-11-03
      • 2022-01-23
      相关资源
      最近更新 更多