我将此构造用于表单存储并验证:https://medium.com/@KozhukharenkoN/react-form-validation-with-mobx-8ce00233ae27
有一个商店形式:
import { observable, action, computed } from 'mobx'
import FormStore from './FormStore'
import UserStore from 'stores/UserStore'
class SettingsFormStore extends FormStore {
@observable
form = {
fields: {
email: {
value: UserStore.email,
defaultValue: UserStore.email,
error: null,
rule: 'required|email'
},
},
meta: {
isValid: true,
error: null,
},
}
}
export default new SettingsFormStore()
有一个stor用户:
import { observable, action, computed } from 'mobx'
import * as UserAPI from 'api/UserAPI'
class UserStore {
@observable id
@observable email
constructor() {
this.load()
}
@action setValues(values) {
this.id = values.id
this.email = values.email
}
@action removeValues() {
this.id = null
this.email = null
}
load() {
UserAPI.getMe()
.then(result => {
this.setValues(result.user)
})
}
}
export default new UserStore()
在表单组件中,我从商店收到电子邮件:
const email = SettingsFormStore.form.fields.email.value
但是发送电子邮件的某些原因未定,尽管UserStore.email保留了值......
答案 0 :(得分:0)
我找到了解决方案:
constructor() {
super()
reaction(
() => UserStore.email,
email => {
this.form.fields.email.value = email
}
)
}
答案 1 :(得分:0)
reaction(
() => ({ email: UserStore.email, id: UserStore.id }),
({ email, id }) => {
this.form.fields.email.value = email
...
}
)