簡體   English   中英

獲取 Cannot read property getDate of undefined 錯誤

[英]getting Cannot read property getDate of undefined error

我使用時間戳通過后端 node.js 發送日期,但是當我嘗試訪問前端的 getDate() 等日期函數時,它給了我未定義的信息。 createdAt object 正確打印了整個值,但我想分別訪問日期和時間。 我也想把這個時間轉換成當地的 gmt+5 時間。 我怎樣才能做到這一點?

import React, { useEffect, useCallback, useState } from "react";
import axios from "axios";

const Slip = (props) => {
    const [order, setOrder] = useState([]);

    const loadOrderData = useCallback(async () => {
        axios
            .get(
                "http://localhost:4000/api/orders/one/" +
                    props.history.location.state.orderid
            )
            .then((res) => {
                setOrder(res.data);
            });
    }, [props]);

    const onPrintClick = () => {
        window.print();
    };

    useEffect(() => {
        loadOrderData();
    }, [loadOrderData]);

    return (
        <React.Fragment>
            <br />
            <div className="container">
                <h4>Danny's Fast Food & Pizza</h4>
                <h5>Reciept</h5>
                <span>
                    <h6>{order.createdAt.getDate()}</h6>
                </span>
                <button className="btn btn-dark w-25" onClick={onPrintClick}>
                    Print
                </button>
            </div>
        </React.Fragment>
    );
};

export default Slip;

import React, { useEffect, useCallback, useState } from "react";

const Slip = (props) => {
  const [order, setOrder] = useState({});

  const loadOrderData = useCallback(async () => {
    // Your API call to get the date
    let letDummyOrder = {
      createdAt: new Date()
    }
    setOrder(letDummyOrder)
  }, [props]);

  const onPrintClick = () => {
    window.print();
  };

  useEffect(() => {
    loadOrderData();
  }, [loadOrderData]);

  if (!order.createdAt) {
    return null
  }

  return (
    <React.Fragment>
      <br />
      <div className="container">
        <h4>Danny's Fast Food & Pizza</h4>
        <h5>Reciept</h5>
        <span>
          <h6>Date : {order.createdAt.getDate()}</h6>
        </span>
        <button className="btn btn-dark w-25" onClick={onPrintClick}>
          Print
                </button>
      </div>
    </React.Fragment>
  );
};
export default Slip;

或者,如果您希望呈現除日期以外的所有內容,請替換

<h6>{order.createdAt.getDate()}</h6>

<h6>{order.createdAt?.getDate()}</h6>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM