我有一个像这样的全局变量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
不是不是 1
,而{中的state.tasks
和state.user
{1}}都是HomeScreen
(undefined
已重新安装),当我阅读用户信息之后,无法再次加载任务信息。
为什么退出应用程序时全局变量HomeScreen
不能循环使用,导致再次打开应用程序时此变量仍然存在?退出应用程序后如何重置loadScreens?
PS:如果我打开Android的应用程序列表并在退出应用程序后完全退出应用程序,则不会出现此类问题。