我正在使用reactjs和mobx . 我有一个可观察的Item对象数组,我试图通过观察数组中对象的属性来显示它们并“显示”属性更改 . 更改不是由任何组件上的单击事件触发,而是由对API调用的响应触发 .

我理解数组中对象的属性更改不会触发整个列表重新呈现(这很好),但我不能让它重新呈现应该观察Item的属性的单个Item组件宾语 .

我已经尝试了几种方法来获取数组中的Item对象是可观察的,但这些方法都不适用于我:

  • 调用'extendObservable() from the Item'的构造函数

  • 将props.item分配给用'@observable'装饰的类成员

  • 调用observable构造函数并传入item对象,如下所示:const item = observable(item)

  • 将'hasUnreadData'字段作为单独的prop传递,并通过'observable.box(item.hasUnreadData)使其可观察 .

这是一些简化的示例代码(在typescript中):

class Item {

  id : string
  hasUnreadData : boolean

  constructor (data: any) {
    this.id = data.id;
    // false by default
    this.hasUnreadData = data.hasUnreadData;
  }

}

@observable items: Item[];

// observes the array and re-renders when items are added/removed (this works)
@observer
class ItemListComponent extends React.Component {
  render() {
    return (
      <List> {
        items.map((item: Item, index) => {

          <ItemComponent key={item.id} itemModel={item} />

        }
      }
    )
  }
}

// should observe the 'hasUnreadData' flag and apply different styles when it re-renders (but this does not work, it only displays the initial state)
@observer
class ItemComponent extends React.Component {
  render() {
    const item = this.props.item;
    return (
      <ListItem button divider selected={item.hasUnreadData} />
    )

  }
}


// imagine this is a promise from an API call
API.fetchData().then((itemId: string) => {
  itemToUpdate = items.find(i => i.id === itemId);
  itemToUpdate.hasUnreadData = true; 
  // this does not trigger the ItemComponent to render again as expected.
});

我是否需要克隆或“重新创建”Item对象以触发渲染?或者我在这里犯了一些明显的错误?任何帮助赞赏 .