React - 从helper方法get请求返回对象

时间:2018-03-09 13:07:01

标签: javascript reactjs object helper-functions

我有一个在我的应用程序的很多地方调用的函数,所以我试图把它变成一个帮助方法,只需要在需要的地方导入。我似乎无法从我所称的地方得到回应。我的语法在哪里错了,或者我的方法完全不合适?

我看到了关于如何从Async AJAX请求返回的帖子。这并不能解决我的问题。我知道如何返回回复。我只是不知道如何从一个文件到另一个文件。这是我的问题。

- 帮助功能

export function enforceEmployeeAuth() {
  let response;
  API.get('user/employee_auth', {}, function(res) {
    response = res
    return response
  })
}

它被称为

componentDidMount() {
  let auth = enforceEmployeeAuth();

  // auth is undefined
}

原始功能

enforceEmployeeAuth() {
    API.get('user/employee_auth', {}, function(res) {
      this.setState({
        employee_auth: res.employee_auth,
        company_admin: res.company_admin
      });
    }.bind(this));
  }

1 个答案:

答案 0 :(得分:1)

答案取决于API是否支持承诺的情况。

我将如何处理这两种情况:

1)仅回拨:

---助手功能:

export function enforceEmployeeAuth(cb) {
  API.get('user/employee_auth', {}, cb)
}

---组件

componentDidMount() {
  enforceEmployeeAuth(res => this.auth = res);
}

2)支持承诺

---助手功能:

export function enforceEmployeeAuth() {
  return API.get('user/employee_auth', {});
}

---组件

componentDidMount() {
  enforceEmployeeAuth().then(res => this.auth = res);
}

您还可能希望在回调中使用setState,以便在获取异步数据时重新呈现组件。

相关问题