无法在本机反应中修改全局变量

Can't modify global variable in react native

问题

我想在本机反应中有一个全局计数器,以显示用户在我正在创建的应用程序中有多少通知。

我在名为 global.js:

的文件中创建了一个全局变量
var notifNum = 0;
global.n = notifNum;

然后在我的代码中,我用

导入它
import './global.js'

然后我尝试用

更新它
     global.n = notifNum;

Notif num 是用户拥有的通知数,在函数中定义。问题是 global.n 保持为 0,根本没有改变。

如何编辑 global.n 变量?

这与 React-Native 关系不大,更多的是与 javascript 作为一种语言的工作方式有关。

简而言之,您必须 export 您希望在其他文件中使用的内容。

Global.js

let counter = 0;

const increment = () => {
  counter++;
  console.log('counter_updated', counter);
};

const worker = {
  increment,
  counter
};

module.exports = worker;

我们已经告诉 JS 引擎我们想要在其他文件中导入什么。将它分配给对象并导出对象不是必需的,但允许更清洁 imports/exports IMO.

Component.js

import { counter, increment } from 'pathTo/global';

我们解构导出的对象,现在可以 global.js 文件中的 modify/use 值。

深思

这不是一个理想的解决方案,因为它不是两种方式。增加 global.js 文件中的计数不会更新 component.js.

中的值

这是因为 React 需要更新其状态才能启动组件的 re-render

此外,这不会通过应用程序重新加载持续存在,我相信您会想要通知等内容。

其他解决方案

  1. 将通知计数存储在数据库中。
  2. 使用组件 state 来管理计数。
  3. 使用像 ReduxMobX
  4. 这样的状态管理器

有一种修改 global.foo 变量的 hacky 方法。

不工作

global.foo = 'foo'; //this cant be changed
global.foo = 'foofoo';
console.log(global.foo); //foo

有效

global.foo = ['foo']; //this can be changed
global.foo[0] = 'foofoo';
console.log(global.foo[0]); //foofoo