react-native - react-native 退出应用程序时如何清除全局变量
问题描述
我有一个usersSerivce.js
像这样的全局变量:
let user = null;
let loadedScreens = {};
/**
* Return user information and the number of times this screen gets user information
* @param {string} The screen name
* @returns Promise<{user:any,loadCount:number}>
*/
export function getUser(screenName) {
return Promis.resolve(user).then(_usr => {
if (!_usr) {
return ajax.get("get user api"); // a Promise
} else {
return _usr;
}
}).then(_usr => {
//Here, I have user information.
user = _usr;
//Record the screen load user count.
loadedScreens[screenName] = (loadedScreens[screenName] || 0) + 1;
return {
loadCount: loadedScreens[screenName],
user
};
});
}
并且在HomeScreen.js
import { getUser } from "./usersService";
import { NavigationEvents } from 'react-navigation';
export default class HomeScreen extend Component {
screenFocus(e) {
getUser(this.props.navigation.state.routeName).then(({user,loadCount})=>{
this.setState({user});
if (loadCount === 1) { //The problem appears in this line
//Here, in order to prevent the user from loading the page data each time the Home page is entered,
//the loading is performed only when the user information is read for the first time.
ajax.get("get current user tasks list API").then(tasks=>{
this.setState({tasks});
})
}
})
}
render(){
return (
<View>
<NavigationEvents onDidFocus={(e)=>this.screenFocus(e)}/>
{/*other components*/}
</View>
)
}
}
这似乎没有任何问题。
但在 Android 中,我单击hardware [return]
按钮退出应用程序。当我再次打开应用时,loadCount
返回的getUser
is not 1
,state.tasks
和state.user
inHomeScreen
都是undefined
(HomeScreen
已重新挂载),当我读取用户信息后,无法再次加载任务信息。
为什么loadedScreens
应用退出时全局变量没有被回收,导致再次打开应用时这个变量仍然存在?应用退出时如何重置 loadScreens?
PS:如果我在退出应用后打开安卓的应用列表并彻底退出应用,就没有这个问题了。
解决方案
推荐阅读
- javascript - 映射函数返回 if
- http - 如何在 ESP32 CAM 上将图像发布到 imgbb.com?我得到“空上传源”。
- python - 在 Pandas DataFrame 中获取前一年的数据
- java - 我需要帮助来构建一个返回数组的方法
- mongodb - MongoDB 聚合 - 读取文档的运算符
- javascript - 是否可以仅使用 CSS 来刻画一个宽度和高度相等的子元素,而不超过它的父元素?
- firebase - 错误:在 null 上调用了方法“round”。接收方:null 尝试调用:round()。构建小部件时抛出错误
- list - 在颤动中动态制作 TabBarView
- python - 为什么代码到达异常块?
- javascript - 如何在 Robo3T 的文档中使用数组更新字符串?