[英]React - Return object from helper method get request
我有一個在我的應用程序的很多地方都被調用的函數,所以我試圖把它變成一個輔助方法,然后在需要的地方導入。 我似乎無法從我打電話的地方得到回應。 我的語法哪里錯了,或者我的方法完全不合適?
我看到了關於如何從異步 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 是否支持 promises 的情況。
這就是我將如何處理這兩種情況:
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,以便在您獲取異步數據時重新渲染組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.