5

我有一个简单的反应表单,在我的 MobX 商店中有两个 observable:

@observable personalInfo = {
        email: '',
        gender: 1,
        birthDate: null, 
        location: ''
    };
@observable personalInfoInEdit = null;

当个人信息的形式被加载(在ctor中)时,我正在我的商店中调用一个方法:

reset_PersonalInfoInEdit() {
        this.personalInfoInEdit = observable(this.personalInfo);
}

它所做的只是重置“编辑中”对象,用原始数据中的数据填充它。如果用户按下“保存更改”,“编辑中”对象将被复制到原始对象。

用另一个 observable 调用 observable() 是否有效?这有什么副作用吗?(它似乎工作)

如果没有,是否有设计模式可以优雅地处理这种“正在编辑”对象的场景。

4

1 回答 1

7

首选模式是使用mobx-utils中的createViewModel实用程序函数。所以你会这样做:

import { createViewModel } from 'mobx-utils'

reset_PersonalInfoInEdit() {
    this.personalInfoInEdit = createViewModel(this.personalInfo);
}

这有一个额外的好处,即在视图模型上具有一些实用功能,使您可以轻松地重置为原始数据或将它们提交给原始模型:

class Todo {
  \@observable title = "Test"
}

const model = new Todo()
const viewModel = createViewModel(model);

autorun(() => console.log(viewModel.model.title, ",", viewModel.title))
// prints "Test, Test"
model.title = "Get coffee"
// prints "Get coffee, Get coffee", viewModel just proxies to model
viewModel.title = "Get tea"
// prints "Get coffee, Get tea", viewModel's title is now dirty, and the local value will be printed
viewModel.submit()
// prints "Get tea, Get tea", changes submitted from the viewModel to the model, viewModel is proxying again
viewModel.title = "Get cookie"
// prints "Get tea, Get cookie" // viewModel has diverged again
viewModel.reset()
// prints "Get tea, Get tea", changes of the viewModel have been abandoned
于 2016-11-23T10:32:29.440 回答