猿问

这些代码怎样复用?

这是微信小程序的代码

1.

if(!this.data.serveItem){
              
                    that.setData({ 
                        loadingHide:false
                    })
                     //请求服务项目列表资源
                    wx.request({
                        url:'https://bird.ioliu.cn/v1?url=http://aasss1.oschina.io/122/4.json',
                        success(res){
                            that.setData({
                                 serveItem:res.data,
                                 tireServices: res.data.tireServices,
                                 maintainServices: res.data.maintainServices,
                                 installServices: res.data.installServices,
                            })
                            getElementHeight('#item-wrap1',that)
                        }
                    })
                }

2.

if(!this.data.rates){
                    that.setData({
                        loadingHide:false
                    })
                    // 请求评价列表资源
                    wx.request({
                        url:'https://bird.ioliu.cn/v1?url=http://aasss1.oschina.io/122/2.json',
                        success(res){
                            that.setData({
                                rates:res.data.rates
                            })
                            getElementHeight('#item-wrap2',that)
                        }
                    })
                }

3.

if(!this.data.recommendList){
                    that.setData({
                        loadingHide:false
                    })
                    // 请求推荐列表资源
                    wx.request({
                        url:'https://bird.ioliu.cn/v1?url=http://aasss1.oschina.io/122/recommendList.json',
                        success(res){
                            that.setData({
                                recommendList:res.data.recommendList
                            })
                            getElementHeight('#item-wrap3',that)
                        }
                    })
                }

上面3段代码重复性高,于是我写了个函数:

function requestResouce(that,oldObj,newObj,url,id){
    if(!oldObj){
        that.setData({
            loadingHide:false
        })
        wx.request({
            url:url,
            success(res){
                that.setData(newObj)
                getElementHeight(id,that)
            }
        })
    }
}

结果代入参数后提示res is not defined。

到底要怎样写才不会出错?

qq_杀意隆_0
浏览 1018回答 1
1回答

Gotta

控制台你看你第几行报错了。似乎不是你写的函数报错,估计方法调来调去,传参哪里传错了。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答