为了使我的React Native代码更加结构化,在我的最新项目中,我决定创建一个包含所有获取请求的类。该课程的结构如下所示:
import { AsyncStorage } from 'react-native';
// const API_URL = 'http://localhost:5500';
const API_URL = 'https://trail-api.herokuapp.com';
export default class Backend {
static logIn(username, password){
fetch(`${API_URL}/users/login`, {
method: 'POST',
headers: {
Accept: 'application/json'
},
body: {
username: username,
password: password
}
});
}
static signUp(firstname, lastname, username, email, password){
fetch(`${API_URL}/users/register`, {
method: 'POST',
headers: {
Accept: 'application/json'
},
body: {
firstname: firstname,
lastname: lastname,
username: username,
email: email,
password: password,
confirmpassword: password
}
});
}
static getUser(){
AsyncStorage.getItem('@Trail:user');
}
static getFeed(username){
fetch(`${API_URL}/user/${username}/feed`);
}
static logOut(user){
AsyncStorage.removeItem('@Trail:user');
}
static followUser(user, username){
fetch(`${API_URL}/users/${username}/follow`, {
method: 'POST',
headers: {
Accept: 'application/json'
}
});
}
static createPost(user, text, longitude, latitude){
fetch(`${API_URL}/posts/new`, {
method: 'POST',
headers: {
Accept: 'application/json'
},
user: user,
body: {
text: text,
location: {
longitude: longitude,
latitude: latitude
}
}
});
}
static likePost(user, id){
fetch(`${API_URL}/posts/${id}/like`, {
method: 'POST',
headers: {
Accept: 'application/json'
},
user: user,
params: {
id: id
}
});
}
static unlikePost(user, id){
fetch(`${API_URL}/posts/${id}/unlike`, {
method: 'POST',
headers: {
Accept: 'application/json'
},
user: user
});
}
static getComments(id){
fetch(`${API_URL}/posts/${id}/comments`, {
method: 'GET',
headers: {
Accept: 'application/json'
}
});
}
}
我希望代码能够工作,如果我将其称为任何组件:
async login(){
const { username, password } = this.state;
await Backend.logIn(username, password)
.then((response) => response.json())
.then((responseJSON) => AsyncStorage.setItem('@Trail:user',
JSON.stringify(responseJSON.user)));
() => navigate('Home');
}
但相反,它会抛出Promise拒绝错误。我有什么遗失的吗? 更新:请查看以下图片中的错误:
答案 0 :(得分:0)
你可以尝试返回获取(这样你可以实际捕获Promise),如下:
static logIn(username, password){
return fetch(`${API_URL}/users/login`, {
method: 'POST',
headers: {
Accept: 'application/json'
},
body: {
username: username,
password: password
}
});
}