如何在函数内导出 JavaScript 中的变量?

问题描述 投票:0回答:1

我有以下功能:

export function request(
  searchKey,
  apiEndpoint,
  path,
  params,
  { additionalHeaders } = {}
) {
  const method = "POST";
  return _request(method, searchKey, apiEndpoint, path, params, {
    additionalHeaders
  }).then(response => {
    return response
      .json()
      .then(json => {
        var my_json = update(params)
        const result = { response: response, json: json };
        return result;
      })
  });
}

我想将变量

my_json
导出到另一个.js文件。我已经尝试过使用
export { my_json }
,但只有在文档顶部执行此操作才有效,这在我的情况下不起作用。有人有想法吗?

javascript reactjs export
1个回答
1
投票

您无法导出函数内部的变量,但您绝对可以借助另一个 javascript 文件中编写的

my_json
函数来获取存储在
callback
中的值。 尝试使用:

export function request(
  searchKey,
  apiEndpoint,
  path,
  params,
  { additionalHeaders } = {},
  callback
) {
  const method = "POST";
  return _request(method, searchKey, apiEndpoint, path, params, {
    additionalHeaders
  }).then(response => {
    return response
      .json()
      .then(json => {
        var my_json = update(params);
        callback(my_json);
        const result = { response: response, json: json };
        return result;
      })
  });
}

并在另一个文件中定义一个函数回调,例如:

function callback(data){
    // assign this data to another variable so that one can use it
    console.log(data)
}

并且在调用请求函数时添加一个参数作为回调。

希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.