我有一个简单的反应表单,以及我的MobX商店中的两个observable:
@observable personalInfo = {
email: '',
gender: 1,
birthDate: null,
location: ''
};
@observable personalInfoInEdit = null;
Run Code Online (Sandbox Code Playgroud)
当加载个人信息的形式时(在ctor中)我在我的商店调用一种方法:
reset_PersonalInfoInEdit() {
this.personalInfoInEdit = observable(this.personalInfo);
}
Run Code Online (Sandbox Code Playgroud)
它的用量只是重置"编辑中"对象,用原始数据中的数据填充它.如果用户按"保存更改",则"编辑"对象将被复制到原始对象.
用另一个observable调用observable()是否有效?对此有任何副作用?(似乎工作)
如果没有,是否有设计模式可以优雅地处理"编辑"对象的这种情况.
首选模式是使用mobx-utils中的createViewModel实用程序函数.所以你会这样做:
import { createViewModel } from 'mobx-utils'
reset_PersonalInfoInEdit() {
this.personalInfoInEdit = createViewModel(this.personalInfo);
}
Run Code Online (Sandbox Code Playgroud)
这有一个额外的好处,就是在视图模型上有一些实用功能,可以让你轻松地重置为原始数据或将它们提交给原始模型:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3202 次 |
| 最近记录: |