LoginSignup
9
7

More than 3 years have passed since last update.

react-waypointを使って無限スクロールを実装する

Posted at

概要

最近、フリーワードで写真検索できるのを作りました。
こちらです。

使ったAPIはunsplashです。

ここでは、写真を配列で保存してコンポーネント側でマップで回しています。
下までスクロールするたびに配列に追加する関数を作る方法を見ていきます。

インストール

yarn add react-waypoint

公式

書いていく

ここでは色々書いていますが、写真配列のコンポーネント周辺だけを見ていきます。

components/MainPage.js
import { Waypoint } from 'react-waypoint';

return (
  <ImageListContainer>
    <Images /> //イメージコンポーネント
    <Waypoint onEnter={this.loading} />
      {loading && (
        <div style={{ position: 'absolute', bottom: '2rem' }}>
          <Waiting /> //非同期の間のローディングコンポーネント
        </div>
      )}
  </ImageListContainer>
);

const mapStateToProps = state => {
  return {
    loading: state.photo.loading
  };
}

ここでは下までスクロールした時に発火さしたいと思うコンポーネントの下に<Waypoint />を起きます。
<Waypoint />につけるonEnterで発火したい関数を起きます。そのほかのオプションについては公式を見てください。
ここでは関数の中は割愛します。
<Waiting />はAPIとの通信で写真を取得しているのですが、その非同期の間にアイコンなどを出すためのコンポーネントです。

以上でできると思いです。

余談

ここからは自分用メモです。
アクションでAPIとの通信をして、写真を配列で取得しているのですが、reducerで保存する時に少しハマりました。

reducers/photoReducer.js
const initialState = {
  photos: [],
  term: '',
  isPhotos: null,
  page: 1,
  loading: true
};

case 'ADD_PHOTOS':
  return {
    ...state,
    // photos: [ ...state.photos, action.payload.photos ], こうするとエラー
    photos: state.photos.concat(action.payload.photos),
    page: action.payload.page,
    loading: false
  };

上のエラーが起きるのは、配列の中に配列を保存しちゃっているので、こういう時はconcatを使うといいみたいですね。学びました。

ただ、photos: [ ...state.photos, ...action.payload.photos ]だといけたのかな?

9
7
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
9
7