react-native动态获取/设置配置变量(API URL)

时间:2018-09-27 12:58:14

标签: javascript reactjs react-native asynchronous react-redux

我的应用程序首先选择一个国家,我想根据用户选择的国家/地区数据更改我的API_URL。

我的country_id存储在AsyncStorage中。我已经尝试过了,但是没有用。

function Configure() {
    let url = '';
}
Configure.prototype.getApiUrl = function (params = null) {
    AsyncStorage.getItem("country").then((value) => {
        if(value == 223) {
            return "https://www.website.com/usa_api"
        }else{
            return "https://www.website.com/api"
        }
    });
}

module.exports = Configure

1 个答案:

答案 0 :(得分:0)

您必须返回Promise函数

function Configure() {
    let url = '';
}

Configure.prototype.getApiUrl = function (params = null) {
    return AsyncStorage // Have to return the promise
        .getItem("country")
        .then((value) => {
            if (value == 223) {
                return "https://www.website.com/usa_api"
            } else {
                return "https://www.website.com/api"
            }
        });
}

module.exports = Configure

用法

现在我们正在返回Promise,我们可以在您要使用它的地方等待它

// Use the promise
Configure
  .getApiUrl()
  .then((apiURL) => {
      // You should be getting the API URL here
  })


// Or better looking code with async/await
const apiURL = await Configure.getApiUrl();
// You should be getting the API URL here