gpt4 book ai didi

javascript - React - 从辅助方法获取请求返回对象

转载 作者:行者123 更新时间:2023-12-03 02:20:10 26 4
gpt4 key购买 nike

我有一个在我的应用程序的许多地方调用的函数,因此我尝试将其转换为辅助方法,然后在需要的地方导入。但我似乎无法从我打电话的地方得到回应。我的语法哪里错了,或者我的方法完全不对?

我看到了关于如何从异步 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));
}

最佳答案

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

这就是我处理这两种情况的方式:

1) 仅回调:

--- 辅助函数:

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

--- 组件

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

2) 支持 Promise

--- 辅助函数:

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

--- 组件

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

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

关于javascript - React - 从辅助方法获取请求返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49194507/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com