所以就像我提到的,DOMContentLoaded 中的代码仅在我刷新页面时运行,但如果我导航到所述页面,我的表中的数据将不再显示。我在这里看到了一个非常相似的帖子(DOMContentLoaded 在导航后不触发,但在使用 javascript_pack_tag 时在页面重新加载时触发)但我无法为我自己的代码找出解决方案。这就是我的代码的样子:
import React from "react";
import "../Styles/Admin.css";
import fetch from "../axios";
const AdminDbCl = () => {
document.addEventListener("DOMContentLoaded", function () {
fetch
.get("http://localhost:9000/getClienti")
.then((data) => loadHTMLTable(data["data"]));
});
function loadHTMLTable(data) {
const table = document.querySelector("table tbody");
if (data.length === 0) {
table.innerHTML =
"<tr><td class='no-data' colspan='11'>No Data</td></tr>";
return;
}
let tableHtml = "";
try {
for (var i in data) {
data[i].map(
({ id_cl, nume_cl, prenume_cl, adresa_cl, nr_tel_cl, mail_cl }) => {
tableHtml += "<tr>";
tableHtml += `<td>${id_cl}</td>`;
tableHtml += `<td>${nume_cl}</td>`;
tableHtml += `<td>${prenume_cl}</td>`;
tableHtml += `<td>${adresa_cl}</td>`;
tableHtml += `<td>${nr_tel_cl}</td>`;
tableHtml += `<td>${mail_cl}</td>`;
tableHtml += `<td><button className="edit-row-btn" data-id=${id_cl}>Edit</td>`;
tableHtml += `<td><button className="delete-row-btn" data-id=${id_cl}>Delete</td>`;
tableHtml += "</tr>";
}
);
}
} catch (err) {
console.log(err);
}
table.innerHTML = tableHtml;
}