写在前面的话
对于微信提供的小程序开发工具,我的感受就是两个字 难受,四个字非常难受,不管是从功能还是界面上都是如此,经常出现连接后台api莫名卡死,超时等问题。界面上,一旦代码量达到一定程度,不管怎么排版都感觉乱乱的,相比之下后台编辑器eclipse就好看多了(是被微信祸害的么 ^-^)。
问题产生背景
由于pages的某个页面代码量非常多,于是我就想到把一部分变量的定义单独放入某一个文件,然后让page页面引入。

把pages/xx/list/index.js中部分变量的定义,放到了static.js文件中,然后在头部引入:
const staticData = require("./static.js")
ps:其实就是把index.js中data中定义的几个key值放入static.js中了

优化前后对比


奇葩“说”问题
使用 this.setData({samples:[{xx:yy}]}),这种方式修改值时,竟然连staticData.samples的值也被修改了。
这像极了java中的引用值传递。是吗?
解决方案
理论说,想要解决必先需要知道问题原因,但这里情况特殊,我可以冒昧的认为这就是引用值传递导致的问题,于是解决方案也就有了,就是将变量的定义变成方法的定义,如下:

替换成下面

引入的时候由变量的引入编程方法:
samples: staticData.samples,编程samples: staticData.samples(),
这样每次方法返回的都是一个新的变量值,不存在引用传递的情况。
网友评论