现象
基于Vue2开发一个移动端项目的时候遇到一个小问题,打开页面后需要发送请求获取数据,但观察到浏览器在不断发送请求,即使已经拿到数据。
分析
问题出在发送请求代码上,经检查,发现发送请求的代码写在了updated()钩子函数里:
data() {
return {
recipeData: [], // 该数据与网页中的一个列表双向绑定
};
},
created() {
this.getRecipeData()
},
updated() {
this.getRecipeData() // 此方法通过axios发起异步请求,并更新数据recipeData
},
查阅官网API,关于updated()钩子函数找到这样一句话:
WARNING
Do not mutate component state in the updated hook - this will likely lead to an infinite update loop!
(警告:不要在updated()中更新组件状态,这将可能导致无限更新!)
getRecipeData()发起axios请求获得数据并更新了recipeData,但由于recipeData和页面中的列表双向绑定,因此recipeData的更新会触发视图更新,从而触发钩子函数updated(),换言之,getRecipeData()会触发updated(),这又执行了getRecipeData(),于是再次发起了请求,因此陷入了无限发请求的循环。
解决方法
既然getRecipeData()一定会触发updated(),那么就要使getRecipeData()的执行不会再次触发自己,因此只要将getRecipeData()放在需要更新视图的具体功能后面即可,如放在删除数据功能后面,删除数据后再次发起请求获得新数据并更新视图,这样就解决了无限发送请求的问题:
data() {
return {
recipeData: [],
};
},
created() {
this.getRecipeData()
},
...
// 删除数据方法
async deleteRecipeData(id) {
...
this.getRecipeData() // 删除后请求新数据
}