Axios响应过滤异常:记录数量正确但组件未获取预期数据
问题根源与修复方案
嘿,我一眼就瞅出问题所在啦!你当前的代码犯了两个关键小错误:
- 你把
self.items赋值成了过滤后的原始Airtable记录数组,但后面的map操作只是生成了组件需要的格式(把id和fields合并),却完全没把这个转换后的结果赋值给items - 操作顺序有点混乱,应该先把数据转换成你需要的结构,再做过滤(或者反过来,但最终要确保赋值的是处理好的数组)
修正后的代码方案一(先转换结构,再过滤)
methods: { loadItems() { // 初始化变量 const app_id = "ID"; const app_key = "KEY"; this.items = [] axios.get( `https://api.airtable.com/v0/${app_id}/Pages`, { headers: { Authorization: `Bearer ${app_key}` } } ).then(response => { // 先把Airtable的结构转换成组件需要的格式:合并id和fields const formattedRecords = response.data.records.map(item => ({ id: item.id, ...item.fields })) // 再对转换后的数组进行过滤 this.items = formattedRecords.filter(item => item.fxPage === 'TestPage'); }).catch(error => { console.log(error) }) } }
修正后的代码方案二(先过滤,再转换结构)
如果你想减少不必要的转换操作(只转换符合条件的记录),可以先过滤再map:
methods: { loadItems() { const app_id = "ID"; const app_key = "KEY"; this.items = [] axios.get( `https://api.airtable.com/v0/${app_id}/Pages`, { headers: { Authorization: `Bearer ${app_key}` } } ).then(response => { this.items = response.data.records .filter(item => item.fields.fxPage === 'TestPage') .map(item => ({ id: item.id, ...item.fields })) }).catch(error => { console.log(error) }) } }
额外优化小提示
- 用箭头函数替代
function,这样就不需要var self = this来保留上下文啦,箭头函数会自动继承外层的this - 用模板字符串(
`)拼接URL和Authorization头,比字符串加号拼接更清晰
内容的提问来源于stack exchange,提问作者majordomo
相关产品推荐
相关产品推荐

