Vue中如何获取数据库真实ID而非默认ID?附报错排查
问题分析与修复方案
1. 为什么会出现TypeError: Cannot convert undefined or null to object?
你把fetch返回的Promise对象直接赋值给了snapshot,但fetch的Promise只有在then回调里才会拿到真正的响应数据。第二个then里你试图访问snapshot.data,但snapshot是Promise实例,根本没有data属性,所以snapshot.data是undefined,调用Object.keys(undefined)自然会抛出这个错误。
2. 页面ID与数据库不一致的原因
你错误地把遍历对象时的索引键key赋值给了appData.id,这个key不是数据库返回的真实ID;再加上前面的数据源错误(用了不存在的snapshot.data),最终显示的ID肯定和数据库对不上。
修复后的代码
getAllEvents() { var requestOptions = { method: "GET", redirect: "follow", }; fetch("http://localhost:8080/event/getAllData", requestOptions) .then((response) => response.json()) // 直接解析JSON,不用先转文本再解析 .then((result) => { console.log(result); const events = []; // 遍历接口返回的真实数据对象 Object.keys(result).forEach((key) => { let appData = result[key]; // 优先用数据本身带的数据库ID,没有的话再用对象键(如果键是数据库ID的话) appData.id = appData.id || key; events.push(appData); }); this.events = events; }) .catch((error) => console.log("error", error)); }
关键修正点
- 删掉了没用的
snapshot变量,直接用then回调里的result(已解析为JSON的真实响应数据) - 用
response.json()替代response.text()+JSON.parse,更简洁可靠 - 修正ID赋值逻辑:优先取数据自带的数据库ID,避免用遍历索引键冒充ID
内容的提问来源于stack exchange,提问作者takis Paras
相关产品推荐
相关产品推荐

