重新加载应用程序后更新全局变量

时间:2019-08-02 15:13:18

标签: android react-native

我在抽屉组件中定义了一个全局变量。我在同一组件中使用了该变量,并进行了更改,我的方法效果很好

Tile

但是当我重新加载应用程序时,import .... ... const USERID_STORED = "userid_stored"; var userArray = []; var lengthNow = 0; ... class DrawerComponent extends React.Component { _goToMessages = (route) => ( () => { const navigateAction = NavigationActions.navigate({ routeName: route }); this.props.navigation.dispatch(navigateAction); this.props.navigation.closeDrawer(); lengthNow = userArray.length; // change it here } ); ... render ( ... ) } 收回了他的初始值 0

我可以让lengthNow保持其值吗?我该怎么办?

如果您还有其他建议,请给我

1 个答案:

答案 0 :(得分:2)

最好分别创建,隔离和管理全局变量和函数。

const USERID_STORED = "userid_stored";
let userArray = [];
let lengthNow = 0;

function setUserArray(data) {
     userArray.push(data)
}

function getUserArray() {
     return userArray
}

function setlengthNow(data) {
     lengthNow = data
}

function getlengthNow() {
     return lengthNow
}

export {  USERID_STORED, userArray ,
        lengthNow,setUserArray, getUserArray,setlengthNow,getlengthNow }

使用情况

import  {  USERID_STORED, userArray ,lengthNow,setUserArray, getUserArray,setlengthNow,getlengthNow } from "./globalfunction path"

....
setlengthNow(userArray.length) // change it here

如果您不想丢失更新的值,请使用AsyncStorage

async componentDidmount() {
 const checkdata = await AsyncStorage.getItem("lengthNow");

 if(checkdata == null) {
    await AsyncStorage.setItem("lengthNow",userArray.length);
 }

}