Cannot read property 'init' of null 小程序中使用components方法selectComponent遇到的问题

小程序中使用components方法selectComponent遇到的问题以及解决办法

问题描述:
Cannot read property ‘init’ of null ,为null

出现原因:
出现的原因是,我在wxml里有if判断,而此时条件还未满足(num还没有等于1),所以造成null



解决办法:
可以在num为1,也就是if条件成立时,进行selectComponent;
在num设置值为1后,再写上这句: this.oneComponent = this.selectComponent(’#mychart’);

 onLoad: function (options) {
    let that = this;
    that.setData({
      num: 1,//num为1
    });
    this.oneComponent = this.selectComponent('#mychart');
    }

补充:
还有可能出现为null的情况有以下几点:
1、json里usingComponents名与wxml组件名不一致

//test.json
"usingComponents": {
  "ec-canvas": "../ec-canvas/ec-canvas"
  }
  
 //test.wxml

2、通过id设置时,id名不一致,或者不是用‘#’

//test.js
this.oneComponent = this.selectComponent('#mychart');

//test.wxml

3、通过id设置时,id名不一致,或者不是用‘.’

//test.js
this.oneComponent = this.selectComponent('.mychart');

//test.wxml

4、就是上面出现过的,存在if条件判断的,满足条件后再selectComponent

你可能感兴趣的:(小程序)