当我第二次调用我的 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;