我知道这个问题已经存在于StackOverflow上,但是大多数问题和答案都非常古老。 我正在开发一个应用,该应用显然使用 react-native 对 componentDidMount 中的数据库执行访存调用。
我在 componentDidMount 中运行了一个时间间隔,它可以调用查询,并且效果很好。现在,我需要在 componentWillUnmount 内部调用clearInterval(this.interval)
,以停止查询并登录我的应用。
1。
当我按下保存按钮并使用props.navigation.navigate("new Screen", {params})
我在应该使用
props.navgiation.replace("Screen")
的情况下阅读了一个解决方案-但这对我不起作用
2。 第二个重要部分是,当我按下另一个标签(使用底部标签导航器)
时,还需要调用 componentWillUnmount我了解例如堆栈导航器中的屏幕从未真正卸载过。因此,有一种不同的方法来调用 componentWillUnmount ,例如当用户离开屏幕(或失去屏幕焦点)或用户离开特定的routeName之类的东西时。
我的 componentWillUnmount -非常简单:
componentWillUnmount(){
clearInterval(this.interval)
console.log("Component did Unmount")
}
只有在我退出登录屏幕并再次退出登录屏幕时才调用它。
(编辑)我的导航器:
const EintragenStack = createStackNavigator(
{
Eintragen: {
screen: StundenEintragen2,
navigationOptions: {
headerTitle: "Stundenverwaltung",
headerTitleStyle:{
color: "white",
alignSelf: "center"
},
headerStyle:{
backgroundColor: "#a51717"
},
}
}
}
)
const CheckStack = createStackNavigator(
{
Übersicht: StundenChecken,
Monat: Monatsübersicht2, // Monatsübersicht
Tag: TagesübersichtDiff, // Tagesübersicht
Edit: {
screen: StundenEdit,
navigationOptions:{
headerTitle: "Stunden bearbeiten",
headerTitleStyle: {
color: "white",
alignSelf: "center"
},
headerStyle: {
backgroundColor: "#F39237"
}
}
}
},
{
backBehavior: "history"
}
);
const Tabs = createBottomTabNavigator(
{
Eintragen: EintragenStack, // StundenEintragen
Checken: CheckStack,
Logout: Logout
},
{
backBehavior: "history",
tabBarOptions: {
labelStyle: {
fontSize: 12,
color: "black"
},
activeTintColor: "red",
activeBackgroundColor: "#ccc"
}
}
);
const AppNavigator = createSwitchNavigator({
Login: Auth, //SecondAuth,
Tabs: Tabs,
});
EintragenStack.navigationOptions = {
tabBarIcon: () => {
return <Icon style={{marginTop: 5}} size={34} name="ios-add-circle-outline" color="green" />;
}
};
CheckStack.navigationOptions = {
tabBarIcon: () => {
return <Icon style={{marginTop: 5}} size={34} name="ios-calendar" color="black" />;
}
};
Logout.navigationOptions = {
tabBarIcon: () => {
return <Icon style={{marginTop: 5}} size={34} name="ios-power" color="red" />;
}
};
const AppContainer = createAppContainer(AppNavigator);
export default AppContainer;
!新编辑!
我实际上已经解决了我的需要,但是问题仍然存在。 我不知道这是否是一个好方法,但是对我来说,我是这样的:
checkUnlockHandler
中致电componentWillMount
。checkUnlockHandler
到if时,如果他告诉他不再需要跑步了,我打电话给clearInterval(this.interval("here is my checkUnlockHandler"))
componentDidMount
中的间隔停止运行,这很好。componentDidMount
内部和该函数内部调用一个函数以告知间隔何时停止,感觉很奇怪。答案 0 :(得分:1)
在使用底部标签导航器时,我遇到了同样的问题,并且找到了适用于我的简单解决方案。
componentDidMount()
{
this.props.navigation.addListener('focus', async () =>{
this.interval= setInterval(() => {
//---------
}, 5000);
});
this.props.navigation.addListener('blur', () => {
clearInterval(this.interval);
});
}
在功能组件中,我们也可以使用useEffect进行清理。
React.useEffect(() => {
navigation.addListener('focus', () => {
this.interval= setInterval(() => {
//---------
}, 5000);
});
return () =>{
clearInterval(this.interval);
};
}, [navigation]);