第二次获取时如何追加数据

IT技术 reactjs firebase google-cloud-firestore
2021-04-28 03:56:36

当我第二次调用我的 fetch 方法时,我无法附加我的数据。在初始渲染时,我的组件从我的数据库中获取数据并将其存储在我的 followingData 状态中。然后,当我滚动到底部时,我再次调用我的 fetchData 函数,但不是将我的新数据附加到 followingData 状态,而是替换它,现在只有新数据显示在我的屏幕上。

这是代码:

function Following({route, navigation}) {
  const [followingData, setfollowingData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [lastVisible, setLastVisible] = useState();

  const fetchData = () => {
    const dataaRef = firestore().collection('usernames');
    const dataRef = firestore().collection('usernames');

    dataRef
      .doc(route.params.username.toLowerCase())
      .collection('Following')
      .onSnapshot(() => {
        dataaRef
          .doc(route.params.username.toLowerCase())
          .collection('Following')
          .orderBy('followedAt')
          .startAfter(lastVisible || 0)
          .limit(7)
          .get()
          .then((snapshot) => {
            snapshot.empty
              ? null
              : setLastVisible(
                  snapshot.docs[snapshot.docs.length - 1].data().followedAt,
                );
            let promises = [];
            snapshot.forEach((doc) => {
              const data = doc.data();
              promises.push(
                data.path.get().then((res) => {
                  const userData = res.data();
                  return {
                    profileName: doc.id ? doc.id : null,
                    displayName: userData.displayName
                      ? userData.displayName
                      : null,
                    followerCount:
                      userData.followers !== undefined ? userData.followers : 0,
                    followingCount:
                      userData.following !== undefined ? userData.following : 0,
                    imageUrl: userData.imageUrl ? userData.imageUrl : null,
                  };
                }),
              );
            });
            Promise.all(promises).then((res) => {
              setfollowingData(res);
            });
            setLoading(false);
          });
      });
  };

  useEffect(() => {
    const dataRef = firestore().collection('usernames');

    const cleanup = fetchData();

    return cleanup;
  }, [route.params.username]);

  return (
    <>
      <View
        style={styles}>
        <TouchableOpacity onPress={() => navigation.openDrawer()}>
          <Icon name="menu" color="#222" size={30} />
        </TouchableOpacity>
        <Text style={{left: width * 0.05}}>Following</Text>
      </View>

      {loading ? (
        <ActivityIndicator size="large" color="black" />
      ) : (
        <>
          <FolloweringScreens
            data={followingData}
            screen={'Following'}
            username={route.params.username}
            navigation={navigation}
            fetchData={fetchData}
          />
        </>
      )}
    </>
  );
}

export default Following;

子组件如下所示,在滚动到末尾时调用 fetchData:

function FolloweringScreens({
  data,
  screen,
  username,
  navigation,
  fetchData,
  setNext,
}) {

  return (
    <>
      <FlatList
        scrollEnabled={true}
        onEndReachedThreshold={0}
        onEndReached={fetchData} <<-- CALLING FETCHDATA AGAIN TO GET MORE DATA
        data={data}
        keyExtractor={(i, index) => index.toString()}
        renderItem={({item, index}) => {
          return (
                  (I use my data here)
          );
        }}
      />
    </>
  );
}

export default FolloweringScreens;
1个回答

如果您只想追加新数据,那么最好setState 中使用回调函数

Promise.all(promises).then(res => {
  setfollowingData(oldState => ({...oldState, ...res}));
});

在这里,您从旧状态中获取所有值,将其放入一个新对象中并向其中添加新数据。如果您的状态是一个数组,则必须将{}[]交换

Promise.all(promises).then(res => {
  setfollowingData(oldState => ([...oldState, ...res]));
});

更新:添加示例