【问题标题】:Mobx, filter and unshift an array in @computedMobx,过滤和取消移动@computed中的数组
【发布时间】:2019-04-10 23:42:42
【问题描述】:

给定一个包含 id-name-propertyName 集合的可观察数组,我试图过滤掉一个必须绑定到 React 组件中的 html 选择控件的国家/地区数组。我需要在我的选择 html 元素中显示一个空的默认值。 'Country' 的过滤器效果很好,但是在添加 .unshift(empty) 部分时我遇到了问题。

我的观察者:

class ReferenceStore {
  @observable referenceData=[];

到目前为止我的@computed:

  @computed get countries() {
    var empty = { id: 0, name: '' };
    var test = this.referenceData.filter(x => x.propertyName === "Country").unshift(empty);
    return test; 
  }

问题是此代码在我的组件中导致以下错误消息:

ReferenceStore__.a.countries.map is not a function 

我应该怎么做?谢谢!

【问题讨论】:

    标签: arrays reactjs mobx computed-properties


    【解决方案1】:

    unshift 返回数组的新长度,而不是数组本身。

    你可以先unshift,然后返回数组。

    @computed get countries() {
      var empty = { id: 0, name: '' };
      var test = this.referenceData.filter(x => x.propertyName === "Country");
    
      test.unshift(empty);
    
      return test; 
    }
    

    【讨论】:

    • 好的,现在我明白了。谢谢一百万。
    猜你喜欢
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 2018-08-26
    • 2020-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多