You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Cloud Firebase中的Timestamp值在React Native中显示为日期或字符串?及云存储图片展示方法

Fixing Firestore Timestamp Conversion & Firebase Storage Image Display in React Native

Hey there! Let's tackle your two issues one by one—getting that Timestamp to show up as a readable date, and displaying images from Firebase Storage.

1. Fixing the Timestamp to Date Conversion

The main problem here is that Firestore's Timestamp isn't a plain string or date—it's a special object. When you pull it from the database, you need to convert it to a JavaScript Date first before formatting it. Also, there's a tiny bug in your mezunDurumu check (you used = instead of ==/===) that we'll fix too.

Step-by-Step Fixes:

  • Convert Timestamp to Date: When fetching the dogumTarihi field, use the toDate() method built into Firestore's Timestamp to turn it into a JS Date object.
  • Handle Loading/Undefined States: Since data loads asynchronously, add a fallback for when the date isn't ready yet.
  • Format with date-fns: Use the format function from date-fns to turn the Date object into a readable string (like dd/MM/yyyy).
  • Fix the Mezun Durumu Check: Replace the assignment operator = with the equality operator == (or better, ===).

Modified Code Snippets:

First, update your onSnapshot logic to convert the Timestamp:

this.subscriber = firestore().collection("tablo").doc('J6mAav1kjkcjrMupeOqX').onSnapshot(doc => {
  const data = doc.data();
  this.setState({
    tablo: {
      adSoyad: data.adSoyad,
      yas: data.yas,
      // Convert Timestamp to Date, or set to null if missing
      dogumTarihi: data.dogumTarihi ? data.dogumTarihi.toDate() : null,
      mezunDurumu: data.mezunDurumu,
    }
  });
});

Then, adjust your render method to format the date and fix the status check:

render() {
  // Clean up the mezun durumu logic
  const mezund = this.state.tablo.mezunDurumu ? "Mezun" : "Mezun Değil";
  // Format the date only if it exists, else show a loading message
  const dtarih = this.state.tablo.dogumTarihi 
    ? format(this.state.tablo.dogumTarihi, 'dd/MM/yyyy') 
    : "Yükleniyor...";

  return (
    <View style={{ padding: 20 }}>
      <Text>Ad Soyad: {this.state.tablo.adSoyad}</Text>
      <Text>Yaş: {this.state.tablo.yas}</Text>
      <Text>Doğum Tarihi: {dtarih}</Text>
      <Text>Mezun Durumu: {mezund}</Text>
    </View>
  );
}

2. Displaying Images from Firebase Storage

To show images stored in Firebase Storage, you'll need to get a download URL for the image file, then use React Native's Image component to render it.

Step-by-Step Setup:

  1. Install Firebase Storage: If you haven't already, install the storage package:

    npm install @react-native-firebase/storage
    # or yarn add @react-native-firebase/storage
    
  2. Update Your Code:

    • Import the storage module and Image component.
    • Add an imageUrl field to your state to store the download URL.
    • Create a function to fetch the download URL asynchronously.
    • Render the image using the URL.

Modified Code Snippets:

First, update your imports:

import React, { Component } from "react";
import { Platform, SafeAreaView, StyleSheet, ScrollView, View, Text, Button, StatusBar, Image } from "react-native";
import firebase from '@react-native-firebase/app'
import firestore from '@react-native-firebase/firestore'
import storage from '@react-native-firebase/storage' // Add this
import { format } from "date-fns";

Update your state:

state = {
  tablo: {
    adSoyad: "",
    yas: "",
    dogumTarihi: null, // Set to null instead of empty string
    mezunDurumu: false,
  },
  imageUrl: "" // Add this for the image URL
};

Add a function to fetch the image URL:

getImageUrl = async () => {
  try {
    // Replace 'images/profile.jpg' with your actual file path in Firebase Storage
    const url = await storage().ref('images/profile.jpg').getDownloadURL();
    this.setState({ imageUrl: url });
  } catch (error) {
    console.error("Error fetching image URL:", error);
    // Handle errors here (e.g., show a placeholder image)
  }
};

Call this function in your constructor:

constructor(props) {
  super(props);
  this.getUser();
  this.getImageUrl(); // Add this
  this.subscriber = firestore().collection("tablo").doc('J6mAav1kjkcjrMupeOqX').onSnapshot(doc => {
    // ... existing snapshot logic
  });
}

Finally, add the Image component to your render method:

render() {
  // ... existing logic for mezund and dtarih

  return (
    <View style={{ padding: 20 }}>
      <Text>Ad Soyad: {this.state.tablo.adSoyad}</Text>
      <Text>Yaş: {this.state.tablo.yas}</Text>
      <Text>Doğum Tarihi: {dtarih}</Text>
      <Text>Mezun Durumu: {mezund}</Text>
      {/* Add the image */}
      {this.state.imageUrl ? (
        <Image
          source={{ uri: this.state.imageUrl }}
          style={{ width: 200, height: 200, marginTop: 20, borderRadius: 100 }}
        />
      ) : (
        <Text style={{ marginTop: 20 }}>Resim yükleniyor...</Text>
      )}
    </View>
  );
}

Notes:

  • Make sure your Firebase Storage rules allow read access to the image (for development, you can set temporary public access, but lock it down for production).
  • Replace 'images/profile.jpg' with the actual path to your image in Firebase Storage.
  • Add error handling to show a placeholder image if the URL fetch fails.

内容的提问来源于stack exchange,提问作者Stayheuh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 10:17:31