MobX:从另一个商店获取数据到商店
MobX: getting data into the store from another store
我将此结构用于表单存储和验证: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()
有一个存储用户:
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 保留了价值...
我找到了解决方案:
constructor() {
super()
reaction(
() => UserStore.email,
email => {
this.form.fields.email.value = email
}
)
}
reaction(
() => ({ email: UserStore.email, id: UserStore.id }),
({ email, id }) => {
this.form.fields.email.value = email
...
}
)
我将此结构用于表单存储和验证: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()
有一个存储用户:
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 保留了价值...
我找到了解决方案:
constructor() {
super()
reaction(
() => UserStore.email,
email => {
this.form.fields.email.value = email
}
)
}
reaction(
() => ({ email: UserStore.email, id: UserStore.id }),
({ email, id }) => {
this.form.fields.email.value = email
...
}
)