第二次获取时如何附加数据 [英] How to append data when fetching a second time

查看:34
本文介绍了第二次获取时如何附加数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am having trouble with appending my data when I call my fetch method a second time. On the initial render, my component fetches data from my database and stores it in my followingData state. Then, when I scroll to the bottom, I call my fetchData function again, but instead of my new data being appended in to the followingData state, it replaces it, and now only the new data is displayed on the my screen.

这是代码:

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:

The child component looks like this, where the fetchData is being called upon when scrolling to the end:

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;

推荐答案

如果只想附加新数据,则最好使用

If you just want to append the new data, then it is better if you use a callback function in your setState:

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

在这里,您从旧状态中获取所有值,将其放在新对象中,然后向其中添加新数据.如果状态是数组,则必须与 [] 交换 {} :

Here you take all the values from the old state, put it in a new object and add the new data to it. If your state is an array, you would have to exchange the {} with []:

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

更新:添加了示例

这篇关于第二次获取时如何附加数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆