API 更新后列表中的重复项
Duplicate items in list after an API update
我正在学习 vuejs 并且正在做一个天气应用程序,目标是使用索引 (humidex) 对城市进行排名。我通过 API (axios) 获取天气信息,以便从多个城市收集数据。我想每 x 分钟自动更新一次数据,问题:我的一些结果是重复的(新数据不会替换旧数据)。
我尝试为每个项目设置一个唯一键(基于纬度和经度),它适用于多个结果,但不适用于所有结果。
data () {
return {
items:[],
show: false,
cities: cities,
newCity:''
}
},
components: {
Item
},
computed: {
sortHumidex() {
return this.items.slice().sort((a,b) => {
return this.getHumidex(b) - this.getHumidex(a) || b.current.temp_c - a.current.temp_c
})
}
},
methods: {
addCity() {
if (this.newCity.trim().length == 0) {
return
}
this.cities.push(this.newCity)
this.newCity = ''
},
getHumidex: (el) => {
const e = 6.112 * Math.pow(10,(7.5*el.current.temp_c/(237.7+el.current.temp_c)))
*(el.current.humidity/100)
return Math.round(el.current.temp_c + 5/9 * (e-10))
},
indexGeo: (e) => {
const lat = Math.round(Math.abs(e.location.lat))
const lon = Math.round(Math.abs(e.location.lon))
return lat.toString() + lon.toString()
},
getApi: function () {
const promises = [];
this.cities.forEach(function(element){
const myUrl = apiUrl+element;
promises.push(axios.get(myUrl))
});
let self = this;
axios
.all(promises)
.then(axios.spread((...responses) => {
responses.forEach(res => self.items.push(res.data))
}))
.catch(error => console.log(error));
}
},
created() {
this.getApi()
this.show = true
}
}
我更新时的渲染 API :
通过推送到现有的项目数组,您必须处理重复项的可能性。每次调用 API 时,只需 替换 items
即可消除此问题。
替换:
responses.forEach(res => self.items.push(res.data))
与:
self.items = responses.map(res => res.data)
我正在学习 vuejs 并且正在做一个天气应用程序,目标是使用索引 (humidex) 对城市进行排名。我通过 API (axios) 获取天气信息,以便从多个城市收集数据。我想每 x 分钟自动更新一次数据,问题:我的一些结果是重复的(新数据不会替换旧数据)。
我尝试为每个项目设置一个唯一键(基于纬度和经度),它适用于多个结果,但不适用于所有结果。
data () {
return {
items:[],
show: false,
cities: cities,
newCity:''
}
},
components: {
Item
},
computed: {
sortHumidex() {
return this.items.slice().sort((a,b) => {
return this.getHumidex(b) - this.getHumidex(a) || b.current.temp_c - a.current.temp_c
})
}
},
methods: {
addCity() {
if (this.newCity.trim().length == 0) {
return
}
this.cities.push(this.newCity)
this.newCity = ''
},
getHumidex: (el) => {
const e = 6.112 * Math.pow(10,(7.5*el.current.temp_c/(237.7+el.current.temp_c)))
*(el.current.humidity/100)
return Math.round(el.current.temp_c + 5/9 * (e-10))
},
indexGeo: (e) => {
const lat = Math.round(Math.abs(e.location.lat))
const lon = Math.round(Math.abs(e.location.lon))
return lat.toString() + lon.toString()
},
getApi: function () {
const promises = [];
this.cities.forEach(function(element){
const myUrl = apiUrl+element;
promises.push(axios.get(myUrl))
});
let self = this;
axios
.all(promises)
.then(axios.spread((...responses) => {
responses.forEach(res => self.items.push(res.data))
}))
.catch(error => console.log(error));
}
},
created() {
this.getApi()
this.show = true
}
}
我更新时的渲染 API :
通过推送到现有的项目数组,您必须处理重复项的可能性。每次调用 API 时,只需 替换 items
即可消除此问题。
替换:
responses.forEach(res => self.items.push(res.data))
与:
self.items = responses.map(res => res.data)