mobx可观察数组已更改,但渲染功能未重新运行

时间:2019-12-11 08:51:24

标签: react-native mobx

@observer
export class BookshelfComponent extends React.Component<{}, {}> {
  @observable
  libraryData: ILibraryBook[] = [{isSelected: false}, {isSelected: false}];

  bookItemPress(index: number) {
    this.libraryData[index].isSelected = !this.libraryData[index].isSelected;
  }

  render() {
    return (

        <FlatList
          data={this.libraryData.slice()}
          renderItem={this.renderItem}
          numColumns={3}/>

    );
  }

  renderItem = ({item, index}) => {
    return (
      <LibraryItemComponent
        bookLibraryItem={item}
        itemClick={() => {
          this.bookItemPress(index)
        }}
      />
    );
  }

}

当我按下一个平面列表项来调用bookItemPress函数时,render函数不会再次运行;

但是当我将一个项目推送到libraryData时,它运行良好!

谢谢!

2 个答案:

答案 0 :(得分:0)

要更新@observable,您可以

  1. 在函数上使用动作装饰器。
  @action.bound
  bookItemPress(index: number) {
    this.libraryData[index].isSelected = !this.libraryData[index].isSelected;
  }
  1. 使用runInAction
  bookItemPress(index: number) {
    runInAction(() => {
       this.libraryData[index].isSelected = !this.libraryData[index].isSelected;
    })
  }

答案 1 :(得分:0)

hide

}

用观察者装饰passed组件可以很好地工作。