LoginSignup
2
1

More than 5 years have passed since last update.

FlatListのonEndReachedにリストの遅延読み込みを仕込むと複数回コールバックする問題

Last updated at Posted at 2018-11-30

前提

前回書いたときに、FlatListは下にスクロールしてリストを追加ロードするのに使うもんだと思い込んでしまった。

なので、前提。
「下方向にスクロールし、端に到達すると次のリストを追加で読み込み、コンテンツが続く限りスクロールできる画面をFlatListを用いて作る」

問題

次のコードのように作ったら、画面遷移してきたときになぜか4回もfetchListが走った。

class ListScreen extends React.Component<Props, States> {
  // ...略...
  componentWillMount() {
    // 前回の記事に書いた件
    // 前に読み込んだリストをクリアしておかないと、最初に一瞬renderされてしまうため
    this.props.clearList();
    // 次のリストを10件取得するアクションをdispatchする関数
    this.props.fetchList();
  }
  // ...略...
  render() {
    return (
      <View>
        <FlatList
          // 下に引っ張ったらリロード
          onRefresh={() => {
            this.props.clearList();
            this.props.fetchList();
          }}
          // onRefreshを書いたら必ず必要な、リフレッシュ中を示すフラグ
          refreshing={this.props.isRefreshing}
          // 端に来たら次のリストを10件取得するアクションをdispatchする関数
          onEndReached={this.props.fetchList}
          // 端の閾値
          onEndReachedThreshold={0.5}
          data={this.props.list}
          renderItem={({ item }) => (
            <ListComponent
              list={item}
            />
          )}
          // ...略...
        />
      </View>
    );
  }
}

解決

次のように書き換えたら、なぜかうまくいった…。
理由がちゃんとわかったら追記します。

class ListScreen extends React.Component<Props, States> {
  // ...略...
  componentWillMount() {
    this.props.clearList();
  }
  componentDidMount() {
    this.props.fetchList();
  }
  // ...略...
}

ヒントになった参考資料

2
1
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
1