0
@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)
        }}
      />
    );
  }

}

when i press a flatlist item to call bookItemPress function, the render function does not run again;

but when i push an item to the libraryData ,it works well!

thanks!!

perry
  • 1
  • 1

2 Answers2

0

To update an @observable, you either

  1. Use action decorator on the function.
  @action.bound
  bookItemPress(index: number) {
    this.libraryData[index].isSelected = !this.libraryData[index].isSelected;
  }
  1. Use runInAction
  bookItemPress(index: number) {
    runInAction(() => {
       this.libraryData[index].isSelected = !this.libraryData[index].isSelected;
    })
  }
Sanyam Jain
  • 1,154
  • 6
  • 9
  • i hava try this! but it not works. the mobx may be thinks the data have not changed. thanks!! – perry Dec 11 '19 at 09:25
0
@observer
export class LibraryItemComponent extends React.Component<ILibraryItemProps> {
   ...
}


@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)
      }}
    />
  );
}

}

It can work well that LibraryItemComponent component decorated with observer.

perry
  • 1
  • 1