繁体   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