admin管理员组文章数量:1326474
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 user8749566user87495662 Answers
Reset to default 2There 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
- Storing the notification counts in a database.
- Using ponent
state
to manage the count. - Using a state manager like
Redux
orMobX
本文标签: javascriptCan39t modify global variable in react nativeStack Overflow
版权声明:本文标题:javascript - Can't modify global variable in react native - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742209180a2433385.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论