首页 > 解决方案 > 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返回的getUseris not 1state.tasksstate.userinHomeScreen都是undefinedHomeScreen已重新挂载),当我读取用户信息后,无法再次加载任务信息。

为什么loadedScreens应用退出时全局变量没有被回收,导致再次打开应用时这个变量仍然存在?应用退出时如何重置 loadScreens?

PS:如果我在退出应用后打开安卓的应用列表并彻底退出应用,就没有这个问题了。

标签: react-nativereact-native-androidreact-navigation

解决方案


推荐阅读