每次打开页面时我都需要发送请求。目前,当我加载应用程序后第一次访问页面时,一切正常,但如果我转到另一个页面并在该请求后返回,则不会再次发送它。
你必须添加焦点侦听器,这样当你返回时,它会刷新数据,如
import * as React from 'react';
import { View } from 'react-native';
function AppScreen({ navigation }) {
React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// The screen is focused
// Call any action and update data
});
// Return the function to unsubscribe from the event so it gets removed on unmount
return unsubscribe;
}, [navigation]);
return <View />;
}
来源:https://reactnavigation.org/docs/function-after-focusing-screen/
这里是一个基于类和基于功能的组件的示例,用于在屏幕的每个负载上运行某些内容。
import React, { useEffect } from "react";
import {View} from 'react-native'
//Functional Component
const App = () =>
{
useEffect(() =>
{
myAction();
}, [])
return (
<View>
</View>
);
}
//Class based Component
class App extends Component
{
componentDidMount()
{
this.myAction();
}
render()
{
return(
<View>
</View>
)
}
}
作为对Nooruddin答案的补充。
在react-navigation 5.x/6.x中,您可以使用
useFocusEffect
钩子,而不是手动添加事件监听器。
import * as React from 'react';
import { View } from 'react-native';
import { useFocusEffect } from '@react-navigation/native';
function Profile() {
useFocusEffect(
React.useCallback(() => {
// Do something when the screen is focused
return () => {
// Do something when the screen is unfocused
// Useful for cleanup functions
};
}, [])
);
return <View />;
}
来源:https://reactnavigation.org/docs/navigation-lifecycle#react-navigation-lifecycle-events