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

javascript - How do I define a global variable in React Native? - Stack Overflow

programmeradmin4浏览0评论

Problem I am creating an app with React Native and firebase. I am using two tabs, and I want to pass the key from inside one tab to another tab (using tabNavigator/reactNavigation for the tabs). I don't know how to define a global variable. I did some reaserch and figured out that I needed to use some sort of .global mand. I've tried using:

var passKey = '';
global.passKey = key; //defined before any screens

and when that didn't work:

this.global.setState({ passKey: item.key }) //defined in button in a flatlist

The statement this.global.setState({}) gives me an error, and global.passKey might save the variable globally, but when I change the variable inside of the screens, one variable doesn't pass over to the other screen. I would really love some help getting a solution to passing a variable between two tabs. Thank you!

Problem I am creating an app with React Native and firebase. I am using two tabs, and I want to pass the key from inside one tab to another tab (using tabNavigator/reactNavigation for the tabs). I don't know how to define a global variable. I did some reaserch and figured out that I needed to use some sort of .global mand. I've tried using:

var passKey = '';
global.passKey = key; //defined before any screens

and when that didn't work:

this.global.setState({ passKey: item.key }) //defined in button in a flatlist

The statement this.global.setState({}) gives me an error, and global.passKey might save the variable globally, but when I change the variable inside of the screens, one variable doesn't pass over to the other screen. I would really love some help getting a solution to passing a variable between two tabs. Thank you!

Share Improve this question edited Nov 21, 2017 at 8:26 nhoxbypass 10.2k13 gold badges50 silver badges73 bronze badges asked Nov 21, 2017 at 6:03 user8749566user8749566
Add a ment  | 

3 Answers 3

Reset to default 3

It works this way:

global.js

export default {};

Usage

import global from './global';

global.passKey = 123;

Although you made your choice of accepted answer, I believe this is what you need.

Well, if it's just a static variable that doesn't change over time, create a constants.js file somewhere in your project and do export const MY_VARIABLE = 'theValue'. After that you can import it into the file which needs it - import { MY_VARIABLE } from './constants'

You have to use redux, if you want to get your variable in two tabs. But if you dont use it before it can be a little plicated when you first start check the docs here https://redux.js/

发布评论

评论列表(0)

  1. 暂无评论