在表单元格内调用javascript函数

在表单元格内调用javascript函数,javascript,reactjs,html-table,Javascript,Reactjs,Html Table,我一直在尝试调用表单元格中的函数来动态生成一些数据。但一直以来都有下面的错误。 我不确定是否在表单元格中正确调用了defined和javascripts函数 TypeError: patient.dob.getFullYear is not a function (anonymous function) C:/Users/Anand/OneDrive/clinic/client/src/components/ListPt.js:64 61 | <td>{patient.

我一直在尝试调用表单元格中的函数来动态生成一些数据。但一直以来都有下面的错误。 我不确定是否在表单元格中正确调用了defined和javascripts函数


    TypeError: patient.dob.getFullYear is not a function
(anonymous function)
C:/Users/Anand/OneDrive/clinic/client/src/components/ListPt.js:64
  61 | <td>{patient.email}</td>
  62 | <td>{patient.mobile}</td>
  63 | <td>{patient.gender}</td>             
> 64 | <td>{calculate_age(new Date(patient.dob.getFullYear(), patient.dob.getMonth(), patient.dob.getDate()))}</td>
     | ^  65 | <td>{patient.address}</td>
  66 | {/* <td><EditTodo todo={todo}/></td> */}
  67 | <td><button className="btn btn-danger" >Add Treatment</button></td>

完整代码如下:

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


const Listpt = () => {
  const [patients, setPatients] = useState([]);


  const getPts = async() =>{
    try {

       const response = await fetch("http://localhost:5000/patients")
       const jsonData = await response.json();


       setPatients(jsonData);

    } catch (err) {
        console.error(err.message);

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


console.log(patients);

//Age calculator
function calculate_age(dob) { 
    var diff_ms = Date.now() - dob.getTime();
    var age_dt = new Date(diff_ms); 

    return Math.abs(age_dt.getUTCFullYear() - 1970);
}

    return <Fragment>
        {" "}
       <table class="table mt-5 text-center">
    <thead>
      <tr>
        <th>OPD No</th>
        <th>Name</th>
        <th>Email</th>
        <th>Mobile</th>
        <th>Gender</th>
        <th>Dob</th>
        <th>Address</th>
      </tr>
    </thead>
    <tbody>

     {patients.map(patient =>(
         <tr key ={patient.patient_id}>
             <td>{patient.patient_id}</td>
             <td>{patient.name}</td>
             <td>{patient.email}</td>
             <td>{patient.mobile}</td>
             <td>{patient.gender}</td>             
             <td>{calculate_age(new Date(patient.dob.getFullYear(), patient.dob.getMonth(), patient.dob.getDate()))}</td>
             <td>{patient.address}</td>

             <td><button className="btn btn-danger" >Add Treatment</button></td>
         </tr>
     ))}
    </tbody>
  </table>
    </Fragment> 

};

export default Listpt;
有人能帮我理解我在第64行哪里出错了吗

<td>{calculate_age(new Date(patient.dob.getFullYear(), patient.dob.getMonth(), patient.dob.getDate()))}</td>
getFullYear是在日期对象上找到的方法

patient.dob不能是日期对象,因为JSON没有这样的对象


它可能是一根绳子。您需要识别该字符串的格式并将其转换为日期对象。

patient.dob不是日期对象的实例。如果是字符串,则可以直接使用new Datepatient.dobpatient.dob很可能是字符串而不是日期。看起来patient.dob不是可以从中调用getFullYear的有效Dtate对象。这不是问题,但是,您的代码受到了FetchAPI中footgun的攻击:在调用json方法之前,您需要通过检查response.ok来检查HTTP是否成功。在我贫血的小博客上详细介绍。添加新日期成功了…谢谢Anurag…干杯!