首页 > 解决方案 > 无法更改 React Native 中的全局变量,它们是只读的吗?

问题描述

我在 React Native 中更改“全局”变量时遇到了最困难和最令人沮丧的时间。我是这门语言的新手,但这应该比它明显的简单得多。似乎“全局”变量是“只读的”并且无法更改……但我发现这难以置信。它与 React Navigation 的使用有关吗?这是一些代码。首先,我创建一个 .js 文件来保存我的“全局”变量对象:

//'globals.js'

module.exports = {
 STATUS: 'false',
};

现在我在“app.js”中的主要代码:

//'app.js'

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';

GLOBAL = require('./globals');  //import the 'global' object and assign name

function HomeScreen({ navigation }) {

 return (
  <>
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center'    }}>
      <Text>Passed GLOBAL: {JSON.stringify(GLOBAL.STATUS)}</Text>  //indicates 'false'...as it should when running for the first time...
      <Text>Home Screen</Text>
    </View>
 {GLOBAL.STATUS === 'false' ? (
        <Button
          title="Go to Login"
          onPress={() => navigation.navigate('Login')}
        />
      ) : (
        <Button title="Do Stuff" onPress={() => navigation.navigate('StuffScreen')} />
      )}
  </>
 );

}

function LoginScreen({ navigation }) {
//do stuff to login here...
var _test = 'dwarves';
GLOBAL.STATUS = _test;

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center'    }}>
      <Text>Stuff Screen</Text>
      <Text>Set Global: {JSON.stringify(GLOBAL.STATUS)}</Text>  //still indicates 'false' even after changing value, should be 'dwarves'...WHY????
      <Button title="Go to Home" onPress={() => navigation.navigate('Home')} />
    </View>
  );
}

function StuffScreen({ navigation }) {
//do 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;

有人可以解释为什么'GLOBAL.STATUS'值在另一个函数中更改时没有传递到'主'屏幕......???作为一个全局变量,这应该是这种情况,但是我发现它不可能实现。感谢您对我对此不理解的任何建议。

标签: react-nativeglobal-variables

解决方案


这是一个简单的方法,更改任何不属于某种状态或道具的变量的值不会导致 React 树重新渲染。

变量正在更改,但您的HomeScreen组件永远不会收到该更改的通知,这是设计使然。你能想象如果每个变量赋值都触发重新渲染,我们会遇到的性能问题吗?

我建议您查看Context API,它允许您向所有组件公开值,并在值更改时通知必要的组件。


推荐阅读