如何在js中通过多个函数多次改变data中的值?
发布于 6 年前 作者 bzou 692 次浏览 来自 官方Issues

在js里通过一个function中获取当前用户的openid,然后存到page里的data中,在其他fuction里再调用data的值返回就是空,请问什么原因?

Page({
  data: {
    useropenid: '',
    my_order_list: []
  },
getopenid_local() {
    var that = this
    wx.cloud.callFunction({
      name: "getopenid",
    }).then(res => {
      that.setData({
        useropenid: res.result.openid
      })
      console.log("data.useropenid: ", that.data.useropenid)
    }).catch(res => {
      console.log("openid获取失败", res)
    })
get_order_list() {
    var that = this
    that.getopenid_local()
console.log("orderlist里的openid:", that.data.useropenid)
    wx.cloud.callFunction({
      name: "get_invite_list",
      data: {
        cloud_openid: that.data.useropenid
      },
      success(res) {
        that.setData({
          my_order_list: res.data
        })
        console.log("成功获取res的数据:", res, that.data.my_order_list)
      }, fail(res) {
        console.log("获取res的数据失败", res)
      }
    })
  },




3 回复

是异步问题。可设置一个标志如 dataready = true。要在dataready时才可以访问openid。另:我是把绝大部分变量都放在 js层 ,而不放在data 中。那些要用在 wxml 页面的,则必须放在data中。比如下述代码中的变量 str1,存取方便。

// index.js
var str1 = ""
Page({
       data:{str2: ""}, 
       func1: function(){},
       func2(){},
    })

function myfunc1(){}
function myfunc2(){}

异步问题,你在使用的时候,还没获取到openid

请学会如何「提问」(👈戳我)

回到顶部