【问题标题】:MobX: getting data into the store from another storeMobX:从另一个商店获取数据到商店
【发布时间】:2017-09-03 09:48:06
【问题描述】:

我将这个构造用于表单存储并验证: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 保留了价值...

【问题讨论】:

    标签: javascript reactjs mobx


    【解决方案1】:
    reaction(
      () => ({ email: UserStore.email, id: UserStore.id }),
      ({ email, id }) => {
        this.form.fields.email.value = email
        ...
      }
    )
    

    【讨论】:

      【解决方案2】:

      我找到了解决办法:

      constructor() {
           super()
      
           reaction(
             () => UserStore.email,
             email => {
               this.form.fields.email.value = email
             }
           )   
      }
      

      【讨论】:

      • 但是有一个问题:如何在一个反应​​中使用来自 UserStore 的多个参数?
      猜你喜欢
      • 1970-01-01
      • 2019-11-20
      • 1970-01-01
      • 2021-11-21
      • 2018-06-11
      • 2020-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多