最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can't modify global variable in react native - Stack Overflow

programmeradmin0浏览0评论

Problem

I want to have a global counter in react native to show how many notifications a user has in an app that I am creating.

I created a global variabal in a file named global.js:

var notifNum = 0;
global.n = notifNum;

then in my code, I import it with

import './global.js'

then later I try to update it with

     global.n = notifNum;

Notif num being the number of notifications a user has, defined in a function. The problem is that global.n stays as 0, and doesn't change at all.

How can I edit the global.n variable?

Problem

I want to have a global counter in react native to show how many notifications a user has in an app that I am creating.

I created a global variabal in a file named global.js:

var notifNum = 0;
global.n = notifNum;

then in my code, I import it with

import './global.js'

then later I try to update it with

     global.n = notifNum;

Notif num being the number of notifications a user has, defined in a function. The problem is that global.n stays as 0, and doesn't change at all.

How can I edit the global.n variable?

Share Improve this question asked Jan 10, 2018 at 2:00 user8749566user8749566
Add a ment  | 

2 Answers 2

Reset to default 2

There is one hacky way to modify a global.foo variable.

Doesn't work

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

Does work

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

This has less to do with React-Native and more to do with how javascript works as a language.

In short, you must export what you wish to use in other files.

Global.js

let counter = 0;

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

const worker = {
  increment,
  counter
};

module.exports = worker;

We've told the JS engine exactly what we want to import in other files. Assigning it to and object and exporting the object is not necessary but allows for cleaner imports/exports IMO.

Component.js

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

We deconstruct the object we exported and are now able to modify/use values in the global.js file.

Food for thought

This is not an ideal solution as it is not two ways. Incrementing the count in the global.js file will not update the value in the ponent.js.

This is because React needs to have it's state updated to initiate a re-render of a ponent.

Also, this will not persist through app reloads, which I believe you would want for something such as notifications.

Other solutions

  1. Storing the notification counts in a database.
  2. Using ponent state to manage the count.
  3. Using a state manager like Redux or MobX
发布评论

评论列表(0)

  1. 暂无评论