如何解决 NextJS 和 firebase 中的此日期时间错误?

问题描述 投票:0回答:1

firebase 数据库正在返回时间戳。 在 redux 的帮助下,我无法将时间戳渲染到组件中,

我该如何解决这个错误。 我需要将时间戳转换为日期或反之亦然

我需要知道有效的类型转换和

import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { Timestamp } from 'firebase/firestore';

interface Order {
  dateTime: Date;
  items: {
    item: {
      id: string;
      image: [];
      name: string;
      price: number;
      rating: number;
      uid: string;
    };
    quantity: number;
  }[];
  shopId: string;
  shopName: string;
  status: string;
  uid: string;
  userEmail: string;
}

interface DataState {
  orders: Order[];
}

const initialState: DataState = {
  orders: [],
};


const convertTimestampToDate = (timestamp: any) => {
  const data = timestamp.toDate().toLocaleTimeString('en-US')
  return data
};


export const OrdersSlice = createSlice({
  name: 'OrderState',
  initialState,
  reducers: {
    setOrders: (state, action: PayloadAction<Order[]>) => {
      state.orders = action.payload.map(order => ({
        ...order,
        dateTime: convertTimestampToDate(order.dateTime),
      }));
    },
  },
});

export const { setOrders } = OrdersSlice.actions;

export default OrdersSlice.reducer;

出现此错误 Authenticated.tsx:106 在操作中检测到不可序列化的值,路径为:

payload.0.dateTime
。价值: 时间戳{秒:1714486856,纳秒:18560000}

看一下调度此操作的逻辑:
{类型:'OrderState/setOrders',有效负载:Array(1)}

(参见 https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serialized-why-should-my-action-types-be-常数) (要允许不可序列化的值,请参阅:https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serialized-data

javascript firebase google-cloud-firestore next.js
1个回答
0
投票

您的

dateTime
属性仅允许 Date 对象:

  dateTime: Date;

但是,您要将 Firestore 时间戳转换为字符串:

        dateTime: convertTimestampToDate(order.dateTime),


const convertTimestampToDate = (timestamp: any) => {
  const data = timestamp.toDate().toLocaleTimeString('en-US')
  return data
};

convertTimestampToDate 返回一个字符串,因为 toLocalTimeString 返回一个字符串。

您应该将时间戳转换为 Date 对象并将其传递。 Timestamp.toDate() 返回一个日期:

      state.orders = action.payload.map(order => ({
        ...order,
        dateTime: order.dateTime.toDate(),
      }));

另请参阅:

© www.soinside.com 2019 - 2024. All rights reserved.