6

indexOf在 React 组件中使用基于对象是否在 mobx 可观察数组中来设置按钮样式。

该按钮用于收藏。它将特定列表项的对象推送到存储中称为“收藏夹”的可观察数组中。收藏夹是一个可观察的对象数组。

这是我的按钮中的 ES6 模板文字:

className={`btn-group ${((this.props.store.favorites.indexOf(this.props.data) > -1)) ? 'success' : 'info'}`}

基本上,它是检查对象是否在数组中success,如果为 false ,则className 将是info

当收藏夹数组处于本地状态时,这非常有效。但是我知道收藏夹数组中的对象一旦进入可观察数组,它们的外观就会有所不同。我知道可观察的数组收藏夹与本地数组收藏夹不同。

但是如何测试一个对象是否在一个可观察的对象数组中呢?我尝试slice()peek()使用 findIndex 但没有骰子。

4

2 回答 2

5

关于文档: isObservableArray

如果给定对象是一个使用 mobx.observable(array) 可观察的数组,则返回 true。

所以要知道是否data在一个可观察的favorites数组中:

// If data is a primitive
className={`btn-group ${mobx.isObservableArray(this.props.store.favorites) && this.props.store.favorites.indexOf(this.props.data) > -1 ? 'success' : 'info'}`}

// Id data is an object it is a little more verbose and coupled to your data
// structure. You have to use the `find` function to iterate and test if an 
// element in the array has the same id.
className={`btn-group ${mobx.isObservableArray(this.props.store.favorites) && !!this.props.store.favorites.find(fav => fav.id === this.props.data.id) ? 'success' : 'info'}`}

这是一个带有函数助手的 POC:https ://jsbin.com/botijo​​m/edit?js,console

于 2017-04-19T14:05:22.167 回答
3

Michel(mobx 创建者)通过Gitter 频道给了我所需的提示。

我实际上需要一个浅层可观察的数组,而不是一个深度可观察的数组。我不需要数组中对象的每个属性都是可观察的(因此我之前看到的对象属性的所有集合/获取),只是添加或删除对象。

所以我把它从

@observable favorites = []

 @observable favorites = observable.shallowArray();

最终,尽管@dagatsoin 的答案是正确的,但如果您需要使用深度可观察的数组。

于 2017-04-20T03:58:16.823 回答