我正在尝试将某项添加到可观察数组中或从可观察数组中移除时触发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();
答案 0 :(得分:1)
您的reaction
是错误的。现在,只有完全更改数组(新引用)时才会触发它。为了触发反应,您需要为数组的watch
属性设置length
。但是,现在要传递给副作用的参数将只是数组长度。
myReaction = reaction(
() => this.testRunFilters.length,
(thisIsLengthNow) => {
console.log('Hello!' + testRunFilters);
}
);
但是您总是可以从reaction
返回更多内容,也可以仅使用this.testRunFilters
来访问数组。