【发布时间】:2021-02-19 03:13:13
【问题描述】:
我正在用 react native 编写一个应用程序,它需要调用 API 以接收将用于所有其他 API 调用的不记名令牌,但我很难确保获取令牌的调用在进行任何其他调用之前完成。
我有一个基本的 APIHelper 类,它将包含应用程序需要进行的所有 API 调用的包装函数,这是它的简化版本:
export class APIHelper {
constructor(baseURL) {
this.baseURL = baseURL;
this.token = null;
}
setToken(token) {
this.token = token;
}
getToken(username, password) {
var url = this.baseURL + `/token/${username}/${password}`;
fetch(url, {
method: "GET",
header: {
"Content-Type": "application/json"
}).then(response => response.json())
.then((data) => {
this.setToken(data["access_token"]);
});
}
getRequest(endpoint) {
fetch(this.baseUrl + endpoint, {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + this.token
}
}).then(response => response.json())
.then((data) => {
console.log(data);
});
}
}
这是我的App.js的简化版:
var apiHelper = new APIHelper("URLGoesHere");
class StarterApp extends React.Component {
render() {
apiHelper.getToken("UsernameGoesHere", "PasswordGoesHere");
var users = apiHelper.getRequest("/users");
console.log(users);
return (
//App Content Here
);
}
}
我尝试了许多不同的方法:使 API 调用异步,在 getRequest 函数中进行检查以等待 token 不是 null 但这似乎挂起,移动调用进入应用程序的构造函数。我想做的事可能吗?还是每次我想要调用 API 时都需要调用以获取令牌?
另外:我知道这不是一个特别安全的 API,它是一个学校项目的临时系统,请不要就此提供反馈。
【问题讨论】:
-
从函数返回每个 fetch 调用,然后使用
async render()和await apiHelper.getToken(...),因此下一行将仅在 fetch 完成后运行。 -
我已经尝试过了,但 React Native 似乎不喜欢
render()是async -
对,你不应该在
render()中这样做。在componentDidMount()中执行此操作,然后相应地设置状态。
标签: javascript reactjs react-native