For循环当中调用了函数,不渲染图层,给自定义组件传值产生数据值丢失,如何解决?
发布于 7 年前 作者 yonglu 338 次浏览 来自 官方Issues
_getCategoryDetail(currentIndex) {
  const shoesID = this.data.categories[currentIndex].shoesID
  const details = this.data.categories[currentIndex]
  const categoryData = this.data.categoryData;
  for (let i = 0; i < shoesID.length; i++) {
      categoryData[currentIndex][i] = {
        title: "",
        image: ""
      }
      getShoesDetail(shoesID[i]).then(res => {
        categoryData[currentIndex][i].title = String(res.data[0]._shoesID)
        categoryData[currentIndex][i].image = String(res.data[0]._hostgraph)
      })
  }
  this.setData({
    categoryData

  })

console.log(categoryData[currentIndex])

},

--------------------------------------以上是category.js中的code---------------------------------------


<w-content categoryDetail="{{categoryData[currentIndex]}}"/>

-------------------------------------以上是category.wxml中的code---------------------------------------


把上方category.js中categoryData[currentIndex]传给下方w-content.js中的categoryDetail

-----------------------------------以下是自定义组件w-content中code-------------------------------------

properties: {

  categoryDetail: {
    type: Array,
    observer: function (newVal, oldVal) {
      console.log(newVal)
    }
  }
},

getShoesDetail为调用的查询数据库函数,外面的this.setData不渲染图层,以下是两边打印的结果

上方是w-content.js:9   下方是category.js:67 

1 回复

getShoesDetail(shoesID[i]).then 是异步请求,你 setData 时上面 promise 请求刚开始。一般将用 Promise.all 合并执行异步任务,结束后再 setData。你将 setData 直接放到 then 后面应该也是可以的,就是赋值多次,性能不好。

回到顶部