Javascript 如何将所有URL保持在一个类中,并在react native中访问所需的类

Javascript 如何将所有URL保持在一个类中,并在react native中访问所需的类,javascript,android,react-native,Javascript,Android,React Native,我创建了一个类,例如“allAPI.js” 里面 export default class allAPI extends Component { BASE_URL: 'http://xx:xx:xx:xx/8080/api/app/" Login:BASE_URL+ '/login'; Homepage: BASE_URL + '/home' } 如何将所有url保持在一个位置,并在调用url的地方访问这些url到所需页面。构建一个Global.js module.exports = {

我创建了一个类,例如“allAPI.js” 里面

export default class allAPI extends Component {

BASE_URL: 'http://xx:xx:xx:xx/8080/api/app/"

Login:BASE_URL+ '/login';
Homepage: BASE_URL + '/home'
}
如何将所有url保持在一个位置,并在调用url的地方访问这些url到所需页面。

构建一个Global.js

module.exports = {
  BASE_URL: 'http://google.com',
  COLOR_TEXT: 'blue',
  //etc
};
总的来说,你只需要

GLOBAL = require('./globals');
然后使用链接:

<View><Text>{GLOBAL.BASE_URL}</Text></View>
{GLOBAL.BASE\u URL}

老实说,有很多方法可以做到这一点。您可以通过定义一个类并放置与特定端点对应的所有变量来绕过它。您可以在有意义的上下文中定义特定端点,等等

因为ReactNative没有
基本URL
的定义,所以那里的所有URL都必须是绝对的。这种方法的问题是端点是变量,这意味着由于代码中的错误,您可以在运行时重写它们

遗憾的是,javascript默认情况下不支持类中的
const
字段,但有一个解决方法。就我个人而言,我使用此代码段构建我的端点类:

export default function constantMaker(clazz, variable, value, writable = false, enumerable = true, configurable = false)
{
    Object.defineProperty(clazz, variable, {
        value: value,
        writable: writable,
        enumerable: enumerable,
        configurable: configurable
    });
}
然后这样称呼它:

import makeConstant from "./modules/helper/constant-maker.js";
export default class Constant {

}

makeConstant(Constant, "baseHTTP", "https:");
makeConstant(Constant, "baseUrl", Constant.baseHTTP + "//website.com");
makeConstant(Constant, "apiEndpoint", Constant.baseUrl + "/app/");
makeConstant(Constant, "newsUrl", Constant.apiEndpoint + "news/");
makeConstant(Constant, "clubsUrl", Constant.apiEndpoint + "clubs/");
makeConstant(Constant, "timetableUrl", Constant.apiEndpoint + "workout/timetable/");

导入
constant.js
后,您的端点将作为该类中的字段可用。

问题是我希望在react native中使用常量,并在其他页面中调用这些常量,例如allapi.js中的LOGIN_URL=“”,在LOGIN.js类中调用与callLoginApi(user){fetch('LOGIN_URL',{method:'POST',首先尝试了类似的方法,但无法导入GLOBAL=require('./globals');因此我选择@dragas方法。顺便说一下,非常感谢。:)这是我找到的最好的方法,但我不知道clazz和其他变量用于什么?非常感谢:)clazz是一个类,您可以在其中写入常量,同时其他变量配置是否可以写入、枚举或配置特定字段。