【问题标题】:Display username data from Firestore in React-Native在 React-Native 中显示来自 Firestore 的用户名数据
【发布时间】:2021-04-25 11:35:52
【问题描述】:

我是 React-Native 的新手。我想在屏幕上显示每个用户的名称。目前,我可以使用“currentUser.email”显示电子邮件,但无法从 firestore 获取用户名。 这是代码:

export default function AddScreen({navigation, route}) {
  const [image, setImage] = useState(null);
  const [uploading, setUploading] = useState(false);
  const [title, setTitle] = useState(null);
  const [author, setAuthor] = useState(null);
  const [genre, setGenre] = useState(null);
  const [summary, setSummary] = useState(null);
  const [price, setPrice] = useState(null);
  const [userData, setUserData] = useState(null);

  const user = firebase.auth().currentUser;
  const userId = firebase.auth().currentUser.uid;

..........................................................................

  const getUser = async () => {
    await firestore()
      .collection('user')
      .doc(user.uid)
      .get()
      .then(documentSnapshot => {
        if (documentSnapshot.exists) {
          console.log('User Data', documentSnapshot.data());
          setUserData(documentSnapshot.data());
        }
      });
  };
  const userName = firebase.auth().currentUser.email;
  const submitBookPost = async () => {
    const imageUrl = await postBookImage();
    console.log('Image Url:', imageUrl);

    firestore()
      .collection('user_book')
      .add({
        userId: userId,
        title: title,
        userName: userName,
        bookImg: imageUrl,
        postTime: firestore.Timestamp.fromDate(new Date()),
        author: author,
        genre: genre,
        summary: summary,
        price: price,
      })
      .then(() => {
        console.warn('Book Added!');
        Alert.alert(
          'Book published!',
          'Your book has been successfully added to Market!',
        );
        setTitle(null);
        setAuthor(null);
        setGenre(null);
        setSummary(null);
        setPrice(0);
      })
      .catch(error => {
        console.warn('Something went wrong.', error);
      });
  };

【问题讨论】:

  • 您遇到的错误是什么?

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


【解决方案1】:

如果您的 getUser 函数有效,您可以使用以下命令从同一集合中获取所有用户数据:

db.collection("user").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(doc.id, " => ", doc.data());
    });
});

另请参阅 getting all documents from a collection 上的 Firebase 文档。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多