0

反応ネイティブアプリの通知ページをやっています。無限スクロールと「プルして更新」オプションがあります。ページに入っても動きますし、引っ張ってリフレッシュしても動きます。新しい通知を取得するためにサーバーを呼び出しているように見えますが、配列に連結されていないため、下にスクロールすると問題が発生します。

import React, { useState, useEffect, useCallback, Component } from "react";
import {
  View,
  Text,
  FlatList,
  Button,
  Platform,
  ActivityIndicator,
  StyleSheet,
  ScrollView,
  RefreshControl,
  SafeAreaView,
} from "react-native";
import { useSelector, useDispatch } from "react-redux";
import i18n from "i18n-js";
import Colors from "../../constants/Colors";
import { getNotificationList } from "../../utils/NotificationsUtils";
import Card from "../../components/UI/Card";

const NotificationsScreen = (props) => {
  const [refreshing, setRefreshing] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [page, setPage] = useState(0);
  const [notifications, setNotifications] = useState([]);
  const [error, setError] = useState();

  const dispatch = useDispatch();

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    setNotifications([]);
    setPage(0);

    console.log("-- Refreshing --");

    getNotifications().then(() => {
      setRefreshing(false);
    });
  }, [dispatch, setRefreshing]);

  const fetchMoreNotifications = useCallback(async () => {
    const newPage = page + 7;
    setPage(newPage);
    console.log(
      "FETCH MORE from page " + newPage + " on array of " + notifications.length
    );

    getNotifications().then(() => {
      setIsLoading(false);
    });
  }, [dispatch, getNotifications]);

  const getNotifications = useCallback(async () => {
    setError(null);
    setIsLoading(true);
    try {
      console.log("Get from page " + page);
      // let fromRecord = (page - 1) * 7;
      const retrievedNotifications = await getNotificationList(
        page,
        7,
        true,
        false
      );
      console.log(
        "Setting " +
          retrievedNotifications.response.notifications.length +
          " new notifications on an already existing array of " +
          notifications.length +
          " elements"
      );

      let updatedNews = notifications.concat(
        retrievedNotifications &&
          retrievedNotifications.response &&
          retrievedNotifications.response.notifications
      );
      setNotifications(updatedNews);
    } catch (err) {
      setError(err.message);
    }
    setIsLoading(false);
  }, [dispatch, setIsLoading, setNotifications, setError]);

  useEffect(() => {
    setIsLoading(true);
    getNotifications(page).then(() => {
      setIsLoading(false);
    });
  }, [dispatch, getNotifications]);

  return (
    <View>
      {error ? (
        <View style={styles.centered}>
          <Text>Error</Text>
        </View>
      ) : refreshing ? (
        <View style={styles.centered}>
          <ActivityIndicator size="large" color={Colors.primary} />
        </View>
      ) : !notifications || !notifications.length ? (
        <View style={styles.centered}>
          <Text>No data found</Text>
        </View>
      ) : (
        <FlatList
          refreshControl={
            <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
          }
          data={notifications}
          keyExtractor={(notification) => notification.notificationQueueId}
          onEndReached={fetchMoreNotifications}
          onEndReachedThreshold={0.5}
          initialNumToRender={4}
          renderItem={(itemData) => (
            <View
              style={{
                marginTop: 10,
                height: 150,
                width: "100%",
              }}
            >
              <Card style={{ height: 150, backgroundColor: "white" }}>
                <Text style={{ fontSize: 16, color: Colors.black }}>
                  {itemData.item.text}
                </Text>
              </Card>
            </View>
          )}
        />
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  centered: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
});

export default NotificationsScreen;

最後までスクロールすると、「fetchMoreNotifications」機能がトリガーされ、コンソールに次のように表示されます。

FETCH MORE from page 7 on an array of 0
Get from page 0
Setting 7 new notifications on an already existing array of 0 elements
FETCH MORE from page 7 on an array of 0
Get from page 0
Setting 7 new notifications on an already existing array of 0 elements
FETCH MORE from page 7 on an array of 0
Get from page 0
Setting 7 new notifications on an already existing array of 0 elements
...and so on

ご覧のとおり、以前に通知を保存した場合でも、「要素が 0 の既存の配列」と表示されます。useCallback の依存関係に問題があるのではないでしょうか?

4

2 に答える 2