[英]React Native AsyncStorage: Get Token and Use it in a refactored API fetch
我决定将我所有的 API 调用放在一个单独的文件中,它们都是无状态的。
const get = endPoint => {
let token = "c8c17003468314909737ae7eccd83d4b6eecb792"; //I have put this token here manually
return fetch(endPoint, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Token " + token
}
}).then(response => response.json());
};
在同一个文件中,我有实际的 API 电话。 示例如下。
export const loadGroups = () => {
const endPoint = "https://xxxx.com/api/groups/";
return get(endPoint);
};
当我按如下所示从各种组件调用 API 时,这非常有效。
import { loadGroups } from "../../api";
componentDidMount() {
loadGroups()
.then(responseJson => {
this.setState({
groups: responseJson
});
})
.catch(error => {
console.error(error);
});
}
但是,我想使用 AsyncStorage 来检索存储的令牌,它的应有性质是返回 promise。当我在调用的每个组件中编写获取令牌并将其存储在 SetState 中的函数时,这很有效。 我真的很想重构代码,使用 redux 对我来说很痛苦。
到目前为止,我已经编写了一个文件来获取令牌,它返回一个 promise。
import { AsyncStorage, Text } from "react-native";
const MyToken = async () => {
try {
const retrievedItem = await AsyncStorage.getItem("userToken");
const item = JSON.parse(retrievedItem);
return item;
} catch (error) {
return null;
}
};
export default MyToken;
在 API 文件中,我将上面的代码重写为
const get = endPoint => {
MyToken().then(token => {
console.log(token, "try 1"); //this works
const lookupOptions = {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Token " + token
}
};
return fetch(endPoint, lookupOptions).then(response => {
console.log(response.json(), "promise response,json");
response.json();
});
});
};
但是,每当我在任何组件中调用 loadGroups().then()(如第一个示例)function 时,我都会收到无法解析 loadGroups.then() 的错误
如果没有 state、redux、mobx 有什么方法可以解决这个问题,请记住我希望我的 API 代码在单独模块的无状态函数中。
在get
function V2
中,您没有返回任何Promise
。 要么在get
函数中放入return
语句,例如
const get = endPoint => {
return MyToken().then(
...
);
}
或从该函数显式返回Promise
,请考虑以下代码段
const get = endPoint => {
return new Promise((resolve, reject) => {
MyToken().then(token => {
...
fetch(endPoint, lookupOptions)
.then(response => response.json())
.then(resolvedResponse => {
resolve(resolvedResponse);
}).catch(error => {
reject(error);
});
});
});
};
希望这会有所帮助!
此链接可以帮助您解决 asyncStorage 问题点击这里 [https://blog.logrocket.com/guide-react-natives-asyncstorage/]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.