简体   繁体   English

如何在React Native中定义全局变量?

[英]How do I define a global variable in React Native?

Problem I am creating an app with React Native and firebase. 问题我正在用React Native和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). 我正在使用两个选项卡,并且我希望将密钥从一个选项卡内部传递到另一个选项卡(对选项卡使用tabNavigator / reactNavigation )。 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 command. 我做了一些重新研究,发现我需要使用某种.global命令。 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. 语句this.global.setState({})给我一个错误, global.passKey可能会全局保存该变量,但是当我在屏幕内部更改该变量时,一个变量不会传递到另一屏幕。 I would really love some help getting a solution to passing a variable between two tabs. 我真的很希望获得帮助,以获取在两个选项卡之间传递变量的解决方案。 Thank you! 谢谢!

You have to use redux, if you want to get your variable in two tabs. 如果要在两个选项卡中获取变量,则必须使用redux。 But if you dont use it before it can be a little complicated when you first start check the docs here https://redux.js.org/ 但是,如果您不使用它,那么当您第一次开始使用它时可能会有些复杂,请在此处查看文档https://redux.js.org/

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' . 好吧,如果这只是一个不会随时间变化的静态变量,请在项目中的某个位置创建一个constants.js文件,并export const MY_VARIABLE = 'theValue' After that you can import it into the file which needs it - import { MY_VARIABLE } from './constants' 之后,您可以将其导入到需要它的文件中- import { MY_VARIABLE } from './constants'

It works this way: 它是这样工作的:

global.js 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. 尽管您选择了可接受的答案,但我相信这是您所需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM