coderwhy / hy-event-store

An event-based global state management tool for vue, react, mini-program, ect.
393 stars 45 forks source link

小程序组件的方法中 this指向 state ,导致无法使用setDate #22

Closed zhangjianxin1983 closed 1 year ago

zhangjianxin1983 commented 1 year ago

你好: 在组件ready生命周期中,监听状态变化,回调函数中this指向 state,无法用于设置组件的data;

    lifetimes:{
        ready(){
            store.onState('playlist',this.playlistStore)
        },
    },
       methods: {
        playlistStore(value){
            if(this){
                console.log(this);
                this.setData({
                 tracks:value
                })
            }
        }
    }

1668858258767

zhangjianxin1983 commented 1 year ago

改成如下写法 ,就可以了

store.onState('playlist',(value)=>this.playlistStore.call(this,value))

但是 offState 不知该如何写了

zhangjianxin1983 commented 1 year ago

目前,在组件中是通过如下方式 ,可以正常获取状态数据了

data: {
        tracks:[],
        fn:null,
    },

    lifetimes:{
        ready(){
            this.data.fn = val=>this.playlistStore(val)
            store.onState('playlist', this.data.fn)
        },
        detached(){
            store.offState('playlist',this.data.fn)
        }
    },

    methods: {
        playlistStore(value){
            // console.log('##',this, typeof this,value);
            this.setData({
                tracks:value.tracks||{}
            })
        }
    }