【问题标题】:Mobx store function call in another Observer componentMobx store 函数调用在另一个 Observer 组件中
【发布时间】:2019-01-29 10:43:43
【问题描述】:

我有一个 Mobx 商店,我在 Provider 中传递这个商店,当我在安慰 this.props 时,它显示了 Mobx 商店的结构。

下面是我的 Mobx 商店

import { observable, computed, action, useStrict, runInAction, toJS } from 'mobx';

// useStrict(true);

class OpenPropertiesStore {

  @observable openProperties = {};

  @action
  fetchOpenProperties() {
    fetch(`http://uinames.com/api/`)
      .then(res => res.json())
      .then(data => {
        runInAction(() => {
          this.openProperties = data;
          this.name = "abhinav";
        })
      })
  }

  @computed get getOpenProperties() {
    return this.openProperties;
  }

}

export default new OpenPropertiesStore();

在组件内部,我正在调用 ComponentDidMount 如果我在哪里打印“this.props”,它会显示商店。 但我不能像这样调用函数

@inject('UserStore', 'CityStore', 'OpenPropertiesStore')
@observer
export default class Navigation extends Component {
   componentDidMount = async () => {
      const { CityStore, UserStore, OpenPropertiesStore } = this.props;
      const data = OpenPropertiesStore.getOpenProperties();
   }
}

给我错误

YellowBox.js:67 可能的未处理承诺拒绝 (id: 0): TypeError:OpenPropertiesStore.getOpenProperties 不是函数 TypeError: OpenPropertiesStore.getOpenProperties 不是函数

任何人都知道如何解决这个错误

【问题讨论】:

  • 您的代码有误。而不是在componentDidMount 方法中工作 - 您正在为这个特定组件重新定义它。 componentDidMount = async () => - 你覆盖了方法。但是需要componentDidMount(){ your code here}

标签: react-native mobx mobx-react mobx-state-tree


【解决方案1】:

MobX 计算不应该作为函数调用,像属性一样访问它们。

const data = OpenPropertiesStore.getOpenProperties;

此外,如果您只想从商店返回一个属性 - 无需为它编写单独的 @computed,因为您不会在其中进行任何计算。直接访问就行了

const data = OpenPropertiesStore.openProperties;

【讨论】:

    猜你喜欢
    • 2017-12-02
    • 1970-01-01
    • 2019-03-20
    • 2019-02-24
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    相关资源
    最近更新 更多