wechat-miniprogram / mobx-miniprogram-bindings

小程序的 MobX 绑定辅助库
MIT License
206 stars 20 forks source link

ts this.data.xxx undefined 如何解决? #22

Closed zx1222 closed 2 years ago

zx1222 commented 2 years ago

打印 this.data 是有值的 模板也可以正常显示 但是 console this.data.xxx 就提示undefined Page({ data: <any>{ days: <any>[], day: <any>null, tabIndex: <any>0, rangeIndex: <any>0, isRangeSelected: false }, onLoad(options?) { this.setMobxBindings(); }, setMobxBindings() { this.storeBindings = createStoreBindings(this, { store, fields: ['library'], actions: ['setAppointmentSuccess'], }) }, onUnload() { this.storeBindings.destroyStoreBindings() }, onShow() { console.log(this) console.log(this.data) console.log(this.data.library) // this.getDays(); }, }) image

zx1222 commented 2 years ago

如果定义 library呢 打印仍是初始值并没有变的 请问是什么情况 应该怎么改写

TtTRz commented 2 years ago

如果定义 library呢 打印仍是初始值并没有变的 请问是什么情况 应该怎么改写

这个应该是 mobx 数据注入时机的问题,在 onShow 打印的时候 store 的数据还没有注入到 this.data 中。

具体可以通过两个断点看出来: 在 onShowconsole.log(JSON.stringify(this.data)) setTimeout(() => { console.log(JSON.stringify(this.data)) }, 1000)

这里暂时可以通过在 onShow 生命周期里先显式的调用一下 this.storeBindings.updateStoreBindings() 来解决,然后再访问 this.data.xxxx 的相关数据。

关于库逻辑的修改我再考虑下怎么处理。