正如我所提到的,DOMContentLoaded中的代码仅在我刷新页面时运行,但是如果我导航到该页面,表中的数据将不再显示。我在这里看到了一个非常相似的帖子(DOMContentLoaded not firing after navigation but fires on page reload when using 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;
}发布于 2020-06-13 02:08:29
前面的答案是正确的,因为每个页面都会触发一次DOMContentLoaded事件。当你导航时,它实际上不会导航到其他页面,而是你在同一页上,只是之前的组件正在卸载,而新的组件正在安装。这就是为什么它是单页面应用程序(SPA)。
我建议你使用useEffect钩子而不是使用这个事件。
React.useEffect(()=>{
fetch
.get("http://localhost:9000/getClienti")
.then((data) => loadHTMLTable(data["data"]));
});
},[]) // empty array means this function has no dependency on any value and will be executed when the component is mounted on the dom.或者通过使您的组件成为类来使用componentDidMount方法。
componentDidMount(){
fetch
.get("http://localhost:9000/getClienti")
.then((data) => loadHTMLTable(data["data"]));
});
}发布于 2020-06-13 01:48:31
DOMContentLoaded事件在初始HTML文档完全加载和解析后触发,无需等待样式表、图像和子帧加载完成。
https://stackoverflow.com/questions/62349323
复制相似问题