簡體   English   中英

在表格單元格內調用 javascript function

[英]Calling a javascript function inside a table cell

我一直在嘗試在表格單元格內調用 function 以動態生成一些數據。 但一直低於錯誤。 我不確定我是否在表格單元格中正確調用了已定義和 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是在Date對象上找到的方法。

patient.dob不能是Date object 因為 JSON 沒有這樣的東西。

可能是一個字符串。 您需要識別該字符串的格式並將其轉換為Date object。

暫無
暫無

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

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