首页 > 解决方案 > 跨函数更改变量值,例如 React Native 中的全局变量?

问题描述

我是 React Native 的新手,我正在尝试从另一个函数更改一个函数中设置的变量。这应该类似于将“全局”变量更改为新值。这是我的代码:

import React, { useState } from 'react';
import { Button, Text, TextInput, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

function HomeScreen({ navigation }) {
const [isLogged, setLog] = useState(0);

 return (
  <>
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center'    }}>
      <Text>Home Screen</Text>
    </View>
      {isLogged === 0 ? (
        <Button
          title="Go to Login"
          onPress={() => navigation.navigate('Login')}
        />
      ) : (
        <Button title="Do Stuff" onPress={() => navigation.navigate('Stuff')} />
      )}
  </>
 );

}

function LoginScreen({ navigation }) {
//do login stuff here...
{isLogged => setLog(1)}  //unable to change 'isLogged' to a value of '1'...?
}

function StuffScreen({ navigation }) {
//do some stuff here...
}

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Login" component={LoginScreen} />
        <Stack.Screen name="Stuff" component={StuffScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

我得到的错误表明函数'LoginScreen'中无法识别'isLogged'变量。使用和操作可以在 React Native 中的各种函数之间更改的“全局”变量的正确方法是什么?我提前感谢您的任何建议。

调查另一个用户的建议,似乎“全球”是我需要的,但我仍然遇到困难。这是一些调整后的代码:

var func = require('./global');
global.config = func(0);

function HomeScreen({ navigation }) {
var _status = global.config;

 return (
  <>
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
     <Text>Passed config: {JSON.stringify(_status)}</Text>
     <Text>Home Screen</Text>
    </View>
 {_status === 0 ? (
        <Button
          title="Go to Login"
          onPress={() => navigation.navigate('Login')}
        />
      ) : (
        <Button title="BroadCast" onPress={() => navigation.navigate('BroadCast')} />
      )}
  </>
 );

}

function LoginScreen({ navigation }) {
//do login stuff here...
global.config = func(1);  //new value of "1" does not pass to 'HomeScreen'
 return (
  <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
   <Text>Login Screen</Text>
   <Text>Set Global: {JSON.stringify(global.config)}</Text>  //indicates '0'...WHY?????
   <Button title="Go to Home" onPress={() => navigation.navigate('Home')}    />
  </View>
  );
 }

这是我尝试从外部 .js 文件加载的“全局”文件:

module.exports = function(variable) {    
console.log(variable);
return variable;
}

我的问题是我尝试在“LoginScreen”函数中更改的“global.config”在返回“主”屏幕时不显示更新的值。为什么...????我无法相信在我所知道的任何其他语言中这样一个简单的概念在 React Native 中几乎是不可能的......这比它应该的要复杂得多......任何关于我不理解的建议都非常感谢......这是杀了我。

标签: react-nativeglobal-variablesuse-state

解决方案


推荐阅读