Axios在BottomNavigation处于非活动状态时发送请求



我已经用React Native Paper中的BottomNavigation创建了应用程序。

应用程序tsx:

const App = () => {
const colorScheme = Appearance.getColorScheme()
const isDarkTheme = colorScheme === 'dark'
const theme = isDarkTheme ? CombinedDarkTheme : CombinedDefaultTheme
const [index, setIndex] = React.useState(0)
const [routes] = React.useState([
{key: 'home', icon: 'home'},
{key: 'map', icon: 'compass'},
{key: 'post', icon: 'plus-box'},
{key: 'chat', icon: 'forum'},
{key: 'profile', icon: 'account'},
])
const api: IApiGateway = new ApiGateway()
const getPostsUseCase: GetPostsUseCase = new GetPostsInteractor(api)
const renderScene = BottomNavigation.SceneMap({
home: () =>
HomeScreen({
getPostsUseCase: getPostsUseCase,
}),
map: MapScreen,
post: PostScreen,
chat: ChatScreen,
profile: ProfileScreen,
})
return (
<PaperProvider theme={theme}>
<BottomNavigation
labeled={false}
navigationState={{index, routes}}
onIndexChange={setIndex}
renderScene={renderScene}
activeColor="#ff5500"
/>
</PaperProvider>
)
}

主页屏幕.tsx:

const HomeScreen = ({getPostsUseCase}: Props) => {
const [isLoading, setLoading] = useState(true)
const [data, setData] = useState<Post[]>([])
useEffect(() => {
getPostsUseCase
.execute({
limit: 15,
since: null,
})
.then((page: Page<Post>) => {
setData(page.data)
})
.catch((error: string) => console.error(error))
.finally(() => setLoading(false))
}, [getPostsUseCase])
return (
<SafeAreaView style={styles.frame}>
{isLoading ? (
<Text>Loading...</Text>
) : (
<FlatList
style={styles.list}
data={data}
renderItem={NewsPost}
keyExtractor={item => item.id.toString()}
/>
)}
</SafeAreaView>
)
}

它可以工作,但当我切换到另一个选项卡(而不是主页(时,HomeScreen会一次又一次地向后端发送请求,次数与我在选项卡之间切换的次数一样多。

我是React Native的新手,甚至是React。。。如何卸载非活动组件或防止加载选项卡切换?为什么会发生这种情况?

您每次都在启动主函数App.tsx。

home:((=>

const renderScene = BottomNavigation.SceneMap({
home: () =>
HomeScreen({
getPostsUseCase: getPostsUseCase,
}),

相关内容

最新更新