使用 MobX 对数组进行排序

Sorting arrays with MobX

我们有一个包含 "User" 对象的 MobX 存储,它上面有 "Comments"(数组)。

{
   user: {
       name: "",
       comments: []
   }     
}

在我们看来,我们希望显示按创建日期排序的评论

在视图中绑定值为this.props.store.user.comments.sort(...) 这看起来最初有效,但在评论中添加条目会破坏排序。

addComment = text => this.user.comments.push(....);

阅读时https://github.com/mobxjs/mobx/issues/166

我开始认为我需要以其他方式向视图公开评论数组,我的商店是否应该以某种方式单独公开排序的数组?

魔术很好,直到它停止工作,我在这里:-)

在@Tholle 的回复之后,我尝试了各种选择,但都没有成功。 我得到`this.props.store.sortedEventLog.map 不是函数``

我是不是在做什么奇怪的事情?

class ContactStore {
 constructor() {
  extendObservable(this, {
    loading: false,
    contact: {
      Name: "",
      Email: "",
      CellPhone: "",
      Phone: "",
      AllAreaOfExpertises: [],
      EventLog: [],
      qualityItems: [],
      Tags: []
    },
    AvailableTags: []
  });

  // this doesnt work
  // this.sortedEventLog = computed(() =>
  //   this.contact.EventLog.sort(
  //     (a, b) => b.Audit.Created.Date - a.Audit.Created.Date
  //   )
  // );
}

// this doesn't work either
// sortedEventLog = computed(() =>
//   this.contact.EventLog.sort(
//     (a, b) => b.Audit.Created.Date - a.Audit.Created.Date
//   )
// );

// this doesn't work either
// get sortedEventLog() {
//   return computed(() =>
//     this.contact.EventLog.sort(
//       (a, b) => b.Audit.Created.Date - a.Audit.Created.Date
//     )
//   );
// }

您可以使用 computed 和 return 排序数组:

示例 (JSBin)

class Store {
  @observable user = {
    name: "Eric",
    comments: [{
      text: 'First comment',
      date: Date.now()
    }]
  }

  @computed get sortedComments() {
    return this.user.comments.sort((a, b) => b.date - a.date);
  }

  addComment = text => this.user.comments.push({
    text: Math.random().toString(36).substring(7),
    date: Date.now()
  });
}

或者,您可以在 addComment 函数中使用 replace 在添加新函数时对它们进行排序:

示例 (JSBin)

class Store {
  @observable user = {
    name: "Eric",
    comments: [{
      text: 'First comment',
      date: Date.now()
    }]
  }

  @action addComment(text) {
    this.user.comments.push({
      text: Math.random().toString(36).substring(7),
      date: Date.now()
    });
    const sortedArray = this.user.comments.sort((a, b) => b.date - a.date);
    this.user.comments.replace(sortedArray);
  }
}