如何使用MobX的toJS方法获取JavaScript对象而非Map
解决MobX observable.map转普通JS对象的问题
你当前用observable.map创建了可观察的Map结构,toJS返回的是原生Map实例。要得到普通JavaScript对象,有两种可行方案:
方案一:直接使用普通对象(推荐)
如果不需要Map的特性,完全可以将model定义为普通对象,makeAutoObservable会自动将其转换为可观察对象,此时toJS直接返回普通对象:
configure({ enforceActions: 'always', }) class Store { constructor() { makeAutoObservable(this) } // 替换observable.map为普通对象 model = { name: 'Alex', } } const store = new Store() const Demo = () => { console.log(toJS(store.model)) // 输出: { name: 'Alex' } }
方案二:将现有Map转换为普通对象
如果必须保留observable.map,可以利用原生Map的entries()方法结合Object.fromEntries(),将Map转换为普通对象:
configure({ enforceActions: 'always', }) class Store { constructor() { makeAutoObservable(this) } model = observable.map({ name: 'Alex', }) } const store = new Store() const Demo = () => { const mapObj = toJS(store.model) // 将Map转换为普通对象 const plainObj = Object.fromEntries(mapObj) console.log(plainObj) // 输出: { name: 'Alex' } }
兼容旧环境的替代写法
如果项目需要兼容不支持Object.fromEntries()的环境,可手动遍历Map构建对象:
const plainObj = {} mapObj.forEach((value, key) => { plainObj[key] = value })
内容的提问来源于stack exchange,提问作者Manster
相关产品推荐
相关产品推荐

