LoginSignup
2
0

More than 5 years have passed since last update.

VirtualizedListでimmutable.jsのList型を使うときにハマったポイント

Last updated at Posted at 2018-10-28

TL;DR

(同じく困ってる人向け)以下いい感じにコピペすると使えます。

<VirtualizedList
  data={SOME_IMMUTABLE_LIST_OBJECT}
  keyExtractor={(item, index) => index.toString()}
  getItem={(data, index) => data.get(index)} // VirtualizedListでは必須プロパティ
  getItemCount={data => data.size} // VirtualizedListでは必須プロパティ
  renderItem={item => this._renderItem(item)}
/>

概要

immutable.jsのList型は、要素の引数を能動的に指定できるためとても便利です。
例えばデータベース内のidとListのindexを対応づける、という使い方もできるため、他にも使っている人がいると思います。

しかしimmutable.jsのList型は、FlatListでは使うことができません。その場合は、代わりにその継承元?であるVirtualizedListを使うようにドキュメントで指示されています。
参考: FlatList#data

VirtualizedListでimmutalbe.Listを使う上での注意点をまとめました。

1. getItem, getItemCountプロパティが必須

プロパティを指定し忘れた場合、それぞれ次のようなエラーが出ます。
TypeError: getItem is not a function ...
TypeError: _this.props.getItemCount is not a function ...

また、getItemCountに指定したサイズ分しかループを繰り返してくれません(逆に、ループ回数を自分で指定できるということでもあります)

2. Immutable.Listにはgetメソッドがない

arrayのつもりでうっかりこんな書き方するとエラーになります。
getItem={(data, index) => data[index]}

3. Immutable.Listにはlengthプロパティがない

arrayのつもりでうっかりこんな書き方するとエラーになります。
getItemCount={data => data.length}

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0