添加到可观察数组时,mobx反应无法触发

时间:2020-10-29 17:21:43

标签: reactjs mobx mobx-react

我正在尝试将某项添加到可观察数组中或从可观察数组中移除时触发mobx反应。

当前仅在删除项目时触发

type QueryParam = {
    name: string
    value: string
}

export default class SelectStore {
    rootStore: RootStore;
    constructor(rootStore: RootStore) {
        this.rootStore = rootStore;
    }

    @observable testRunFilters: QueryParam[] = [];

    @action updateTestRunFilter = (queryParam: QueryParam) => {
        const existingParam = this.testRunFilters.find(q => q.name === queryParam.name && q.value === queryParam.value);
        if (!existingParam) {
            this.testRunFilters.push(queryParam);
            //console.log('In updateTestRunFilter' + this.testRunFilters);
        }
    }

    @action removeTestRunFilter = (queryParamName: string) => {
        const existingParam = this.testRunFilters.find(q => q.name === queryParamName);
        if (existingParam) {
            this.testRunFilters = this.testRunFilters.filter(q => q.name !== queryParamName);
            //console.log('In removeTestRunFilter' + this.testRunFilters);
        }
    }

    myReaction = reaction(
        () => this.testRunFilters,
        (testRunFilters) => {
            console.log('Hello!' + testRunFilters);
        }
    );
}

console.log中的updateTestRunFilter被触发了,所以我不确定这是怎么回事?

我也无法使其与Map一起使用,例如@observable testRunFiltersMap = new Map();

1 个答案:

答案 0 :(得分:1)

您的reaction是错误的。现在,只有完全更改数组(新引用)时才会触发它。为了触发反应,您需要为数组的watch属性设置length。但是,现在要传递给副作用的参数将只是数组长度。

   myReaction = reaction(
        () => this.testRunFilters.length,
        (thisIsLengthNow) => {
            console.log('Hello!' + testRunFilters);
        }
    );

但是您总是可以从reaction返回更多内容,也可以仅使用this.testRunFilters来访问数组。