【问题标题】:Mobx consecutive getting computed values produces different referencesMobx 连续获取计算值会产生不同的引用
【发布时间】:2019-09-26 06:39:21
【问题描述】:
class Store {
    @computed get staticItems(): number[] {
        return [1, 2, 3]
    }
}

describe('mobx', () => {
    it('computed static items should be same', (done) => {
        let store = new Store();
        let items = store.staticItems;
        setTimeout(() => {
            expect(items).toBe(store.staticItems);
            done()
        }, 500);
    });
})

使用 jest 进行测试会抛出

Expected: [1, 2, 3]
    Received: serializes to the same string

      50 |         let items = store.staticItems;
      51 |         setTimeout(() => {
    > 52 |             expect(items).toBe(store.staticItems);

这个测试通过toEqual 但失败了toBe 这意味着两个引用指向不同的对象。我错过了什么?使用 react this 会不必要地更改子组件的 props。

【问题讨论】:

    标签: mobx


    【解决方案1】:

    MobX 计算值在没有在反应中使用时会自动挂起。来自documentation

    这种自动悬挂非常方便。如果不再观察到计算值,例如使用它的 UI 不再存在,MobX 可以自动对它进行垃圾回收。这与autorun 的值不同,您必须自己处理它们。有时它会让刚接触 MobX 的人感到困惑,如果你创建了一个计算属性,但没有在反应的任何地方使用它,它就不会缓存它的值,并且比看起来必要的更频繁地重新计算。但是,在现实生活中,这是迄今为止最好的默认值,如果需要,您始终可以使用 observekeepAlive 强制保持计算值处于唤醒状态。

    【讨论】:

      猜你喜欢
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 1970-01-01
      • 1970-01-01
      • 2019-06-21
      相关资源
      最近更新 更多