如何克隆MobX observable? (编辑保存更改)

时间:2016-10-21 21:12:20

标签: reactjs mobx

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

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

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

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

它只需重新设置“编辑中”对象,用原始数据中的数据填充它。如果用户按“保存更改”,则“编辑中”对象将被复制到原始文件。

用另一个observable调用observable()是否有效?对此有任何副作用? (似乎有用)

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

1 个答案:

答案 0 :(得分:6)

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

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