使用Fetch API获取患者数据后,Map函数仅渲染最后一条数据的问题
问题解决:Fetch获取患者列表后仅显示最后一位患者
问题根源
- 重复覆盖innerHTML:
map循环中每次执行pxtselect.innerHTML = ...会清空之前的内容,最终只保留最后一次循环的结果 - 重复添加同一DOM元素:每次循环都把同一个
pxtselect元素添加到pxtbox,DOM元素无法重复挂载,最终页面只显示最后一次添加的内容 - 错误的结构设计:为每个患者单独创建
select,正确逻辑应该是一个select包含所有患者的option
修复后的完整代码
const getData = async(url) => { // 声明response变量,避免全局污染 const response = await fetch(url, { method: "GET", }); return response; }; function setPxt(data) { const pxtbox = document.querySelector(".pxt"); // 清空容器原有内容 pxtbox.innerHTML = ''; // 创建单个select元素 const selectElement = document.createElement("select"); selectElement.name = "patient-select"; // 添加默认提示选项 const defaultOption = document.createElement("option"); defaultOption.value = ""; defaultOption.textContent = "请选择患者"; selectElement.appendChild(defaultOption); // 循环生成所有患者的option data.forEach((pxt) => { const option = document.createElement("option"); option.value = pxt.id; option.textContent = `${pxt.firstname} ${pxt.lastname}`; selectElement.appendChild(option); }); // 将select放入容器并添加到页面 const pxtselect = document.createElement("div"); pxtselect.appendChild(selectElement); pxtbox.appendChild(pxtselect); // 处理选择事件 const form = document.querySelector(".drugs"); const legend = document.createElement("div"); // 初始提示文本 legend.innerHTML = `<p>请选择患者开具处方</p>`; form.appendChild(legend); const selectedInput = document.querySelector("input[name='pxt_id']") || document.createElement("input"); selectedInput.type = "hidden"; // 改为隐藏输入框更合理 selectedInput.name = "pxt_id"; selectedInput.value = ""; form.appendChild(selectedInput); selectElement.addEventListener("change", (e) => { const selectedPatient = data.find(p => p.id === e.target.value); if (selectedPatient) { // 更新处方标题 legend.innerHTML = `<p>为 ${selectedPatient.firstname} ${selectedPatient.lastname} 开具处方</p>`; // 更新隐藏输入框的患者ID selectedInput.value = selectedPatient.id; } else { legend.innerHTML = `<p>请选择患者开具处方</p>`; selectedInput.value = ""; } }); } function setData() { const url = "http://localhost:8000/patients/"; getData(url) .then((response) => response.json()) .then((data) => { console.log(data); if (data && data.length > 0) { setPxt(data); } else { const box = document.querySelector(".pxt"); box.innerHTML = `<p>暂无患者数据</p>`; } }) .catch(err => { console.error("获取数据失败:", err); const box = document.querySelector(".pxt"); box.innerHTML = `<p>获取患者数据失败,请稍后重试</p>`; }); } setData();
关键修改说明
- 结构调整:创建单个
select,循环生成所有option添加到其中,避免重复创建select元素 - 事件处理优化:选择患者后动态更新处方标题和隐藏输入框的患者ID,提升交互体验
- 变量声明规范:为
response添加const声明,避免全局变量污染 - 边界情况处理:增加数据为空、请求失败的提示,完善错误处理逻辑
- 输入框类型优化:将患者ID输入框改为隐藏类型,避免用户手动修改
内容的提问来源于stack exchange,提问作者Pogbogu
相关产品推荐
相关产品推荐

