【问题标题】:How do I print out my object array in React Native Expo?如何在 React Native Expo 中打印出我的对象数组?
【发布时间】:2021-12-29 00:13:35
【问题描述】:

如何打印我在控制台中看到的值?我需要在我使用 Expo 在 React Native 中运行的应用程序中显示它们。我是否需要映射对象数组并打印出值,或者因为 MyProfile 是异步的而以不同的方式运行它?

谢谢!

import { useNavigation } from "@react-navigation/core";
import React, { useEffect, useState } from "react";
import firebase from "firebase/app";
import "firebase/firestore";
import { auth } from "../firebase";
import {
  Text,
  View,
  StyleSheet,
  Image,
  SafeAreaView,
  ScrollView,
  TouchableOpacity,
} from "react-native";
import { Animate } from "react-native-entrance-animation";
import Copyright from "./Copyright";

const ProfileScreen = () => {
  const navigation = useNavigation();

  const MyProfile = () => {
    const [posts, setPosts] = useState(null);
    let myPosts = "Profile loading...";

    const collectIdsAndDocs = (doc) => {
      return { id: doc.id, ...doc.data() };
    };

    useEffect(() => {
      const getPost = async () => {
        const snapshot = await firebase
          .firestore()
          .collection("profiles")
          .where("email", "==", auth.currentUser.email)
          .get();
        myPosts = snapshot.docs.map(collectIdsAndDocs);
        console.log(myPosts);
        setPosts({ myPosts });
      };
      getPost();
    }, []);
    return (
      <View>
        <Text>{/*how do I print out values here!? I see them in console*/}</Text>
      </View>
    );
  };

【问题讨论】:

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


    【解决方案1】:

    既然你已经调用了setPostsuseState钩子,你可以在你的渲染代码中访问posts

    return (
      <View>
         {posts.map((post) => (
           <Text>{post.id}</Text>
         ))}
      </View>
    );
    

    要解决null问题,在定义状态时传入一个空数组作为初始值:

    const [posts, setPosts] = useState([]);
    

    【讨论】:

    • 我收到null is not an object (evaluating 'posts.map')
    • 如果我检查帖子是否为空并正确返回,我会得到undefined is not a function (near '...posts.map...')
    • 在我的回答中查看更新,但也请search for your error messages 继续前进 - 因为这个之前已经介绍过。
    • 我实际上有一个非常愚蠢的错误并将我的 setPosts({myPosts}) 更改为 setPosts(myPosts) 并修复了其余部分,感谢地图!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 2011-09-19
    • 1970-01-01
    • 2019-02-23
    • 2019-05-09
    • 2022-12-11
    • 1970-01-01
    相关资源
    最近更新 更多