【问题标题】:How do I subscribe to @computed object in mobx?如何在 mobx 中订阅 @computed 对象?
【发布时间】:2019-10-24 07:41:10
【问题描述】:

我想订阅一个返回简单对象的计算属性。

代码沙盒:https://codesandbox.io/s/epic-noether-g8g0x

我做了一个简单的例子来说明问题所在:

const zeroSize = {
    width: 0,
    height: 0
};

class Item {
    @observable size = zeroSize;
}

class Collection {
    @observable childrens: Item[] = [];

    @computed get size() {
        return this.childrens.length > 0 && this.childrens[0] ? this.childrens[0].size : zeroSize;
    }

    constructor() {
        reaction(() => this.size, size => {
            // Expected { width: 0, height: 1000 }
            // Actual { width: 0, height: 0 }
            console.log('-----size=', toJS(size));
        });
    }
}

const item1 = new Item;
const collection1 = new Collection;
collection1.childrens.push(item1);
item1.size.height = 1000;

https://github.com/mobxjs/mobx/issues/2176

【问题讨论】:

    标签: reactjs mobx mobx-react


    【解决方案1】:

    您正在监听错误的更改。

    因为你在监听大小的变化,所以高度会触发变化:

    const item1 = new Item; // size === 0
    const collection1 = new Collection; // size === 0
    collection1.childrens.push(item1); // size === 1 (triggers reaction)
    item1.size.height = 1000; // size === 1 (doesn't trigger reaction)
    

    如果您想监听childrens 更改导致的任何和所有更改,那么您需要监听更改。

    reaction(
      () => toJS(this.childrens),
      size => {
        // Expected { width: 0, height: 1000 }
        // Actual { width: 0, height: 0 }
        console.log("-----size=", toJS(this.size));
      }
    );
    

    通过收听toJS(this.childrens),可以订阅childrens的长度何时发生变化,还可以订阅childrens元素的某个属性发生变化的时候。

    如果您只想在添加或删除新孩子时收听,那么收听size 是有意义的。如果您想在添加、删除或修改孩子时收听,那么您需要更改您正在收听的内容。

    这是一个沙盒:https://codesandbox.io/embed/white-hill-fntxt

    以及相关的控制台日志:

    -----size= Object {width: 0, height: 0}
    -----size= Object {width: 0, height: 1000}
    

    【讨论】:

    • @KhusamovSukhrob 是的,我认为你可能需要
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    • 2018-08-26
    相关资源
    最近更新 更多