我在表格上需要它。 我的表单在数据提交中是这样的:
const initial = {
name "",
surname: "",
adresses: new Array() <- this give me warning when array empty *
}
我的地址是对象数组,其中我有一些标准属性,我可以使用extendObservable添加新的属性 地址类型{state:&#39;&#39;,town:&#39;&#39; }
extendObservable(this.props.data['adresses'][i], { [keyName]: '' });
我的问题是,使用extendObservable向地址添加新属性我没有看到(观察)live的任何变化,但是如果在执行extendObservable之后,我更新了state的值,我可以看到新添加的属性。为什么我没有看到新属性我将其添加到地址?
我的商店是这个(打字稿):
const initial = {
namel: "",
surname: "",
addresses: new Array()
}
export class formStore {
constructor() {
this.formData = initial
}
@observable formData: {
[index: string]: any,
name: string,
surname: string,
addresses: any[]
};
@action updatePropertyForm(key: string, value: any) {
this.formData[key] = value;
}
@action updatePropertyAddresses(key: string, value: string, i: number) {
this.formData.addresses[i][key] = value;
}
@action initializeFormData(data: any) {
this.formData = data;
}
@action addEmptyAddress() {
const emptyAddress = {
state: "",
townl: "",
}
this.formData['addresses'].push(emptyAddress);
}
@action addPropertyToAddresses(_keyName: string) {
const length = this.formData['addresses'].length;
for (var i = 0; i < length; i++) {
let keyName = _keyName
keyName = keyName.replace(/\s/g, '')
keyName = toLowerChar(keyName);
extendObservable(this.formData['addresses'][i], { [keyName]: '' });
}
}
@action removePropetyFromAddresses(_keyName: string) {
const length = this.formData['addresses'].length;
for (var i = 0; i < length; i++) {
let keyName = _keyName
delete this.formData['addresses'][i][keyName];
}
}
}
通过调用添加或删除我必须更新其他属性之一,所以我可以看到我添加的新属性。 当我放置新房产时如何观察它?
答案 0 :(得分:2)
正如文档中所述can only observe objects properties which exist during observer init。
如果你想观察一个动态键控对象(作为你的地址对象),你必须使用asMap
修饰符(或者像我在我的例子中那样直接使用mobx.map)
像这样:
// add a first addresse
store.addresses.push(mobx.observable.map({town: "Stormwind", street: "Dwarf lane"}));
// add a props to the first addresse
store.addresses[0].set("number", 2);
这是一个有效的例子。