如何减少请求的数量在React导航TopTabNavigator使用世博会?



我是React Native的新手,目前我正在使用expo开发一个应用程序。我正在使用来自react导航6的TopTabNavigator,我不明白如何减少请求的数量。基本上,只要我点击某个标签,请求就会发出。(因为组件被重新创建-即使我回到以前的标签是相同的,没有数据修改)。我试图使用useFocusEffect从反应导航,但它不像我预期的那样工作。也许我应该在ProfileTabsScreen中提出请求,并通过道具将数据传递给特定的选项卡?

主要组件

const ProfileStatsScreen = (props) => {
const { userId } = props.route.params;
const { initialRoute, username } = props.route.params;
const RatingsDetails = () => <RatingsTab userId={userId} />;
const FollowersDetails = () => <FollowersTab userId={userId} />;
const FollowingsDetails = () => <FollowingsTab userId={userId} />;
return (
<SafeAreaView style={styles.screen}>
<Header title={username} />
<TopTabContainer initialRouteName={initialRoute}>
<Tab.Screen
name="Ratings"
component={RatingsDetails}
options={{ tabBarLabel: "Reviews" }}
/>
<Tab.Screen
name="Followers"
component={FollowersDetails}
options={{ tabBarLabel: "Followers" }}
/>
<Tab.Screen
name="Following"
component={FollowingsDetails}
options={{ tabBarLabel: "Followings" }}
/>
</TopTabContainer>
</SafeAreaView>
);
};

TAB COMPONENT (RATINGS)

export const RatingsTab = ({ userId }) => {
const { user } = useAuth();
const [reviews, setReviews] = useState([]);
const [loading, setLoading] = useState(false);
useFocusEffect(
React.useCallback(() => {
setLoading(true);
axios
.get(`${process.env.BASE_ENDPOINT}/users/${userId}/reviews`, {
headers: { Authorization: `Bearer ${user?.token}` },
})
.then((res) => {
setReviews(res.data.reviews);
setLoading(false);
})
.catch((err) => {
console.log(err);
setLoading(false);
});
setLoading(false);
}, [userId, user?.token])
);
const renderRatings = ({ item }) => {
const { reviewer, rating, review, createdAt } = item;
return (
<CardRatings
avatar={reviewer?.avatar}
name={reviewer?.name}
date={moment(createdAt).format("LL")}
rating={rating}
review={review}
service={"Tuns"}
/>
);
};
return (
<>
{!loading && (
<FlatList
data={reviews}
keyExtractor={(item) => item?._id}
renderItem={renderRatings}
/>
)}
{loading && <Spinner />}
</>
);
};

您非常接近解决方案,您的useFocusEffect配置正确。更改行

useFocusEffect(
React.useCallback(() => {
setLoading(true);

useFocusEffect(
React.useCallback(() => {
if (isLoading) return; 
setLoading(true);

。,如果loading为true,则不要调用axios。虽然这并不能消除额外请求的可能性,但它应该会大大减少您看到的内容。

另外,由于您使用的是。then,因此请将回调的最后一行封装在。finally.

中。
.finally(()=> {
setLoading(false)
});

否则,在promise解析之前,你的加载状态将被设置为false。

谢谢,但不幸的是不工作。让我们假设我已经在RatingsTab中,并且我拥有数据,因为到目前为止已经发出了请求。如果我去FollowersTab,然后我回到RatingsTab,如果数据没有改变,我不想打电话。if (isLoading) return;我认为它不会帮助我,因为加载状态一开始是假的(当重新创建评级选项卡组件时)。

最新更新