简体   繁体   中英

Mobx4 - observable.map .keys() .values() return function instead of array

I am trying to declare an observable.map using the decorate syntax.

class UiStore {
   loaders = observable.map({})
}

export default decorate(UiStore, {
   loaders: observable
})

But when I try to use loaders.keys() it just outputs the function definition, instead of returning a value:

{next: ƒ, Symbol(Symbol.iterator): ƒ}

You are creating an observable from an observable.

class UiStore {
   loaders = observable.map({}) // Creates an observable map
}

export default decorate(UiStore, {
   loaders: observable // creates an observable from the observable map
})

It is enough to do it once (but not the problem here). Your main problem is, that you are expecting the wrong thing. Most map methods return an iterator and not an array as you expect. So your problem has nothing to do with mobx but with your understanding how javascript's Map methods work.

HowTo iterate over an interator

 const { decorate, observable, autorun } = mobx; class UiStore { loaders = new Map() } const decoratedUiStore = decorate(UiStore, { loaders: observable }); const uiStore = new decoratedUiStore(); autorun(() => { for (const key of uiStore.loaders.keys()) { console.log(key); } }); uiStore.loaders.set('name', 'jeff'); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/mobx/4.1.1/mobx.umd.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM