问题描述
我正在尝试查询我本地保存在设备中的用户数据,并使用它进行API调用。 问题是,当我这样做时,AsyncStorage会在75%的时间内为用户返回null,但是在25%的时间内我可以查询用户,而我不知道问题出在哪里。
const [user,setUser] = useState(null)
function getQuote() {
var retrieveData = async () => {
try {
const value = await AsyncStorage.getItem("user");
const data = JSON.parse(value);
setUser(data.user.email);
} catch (error) {}
};
retrieveData();
fetch("http://localhost:3000/apI/Order/",{
method: "POST",body:
"product_id=" +
product._id +
"&user=" +
user +
"&quantity=" +
quote +
"&status=Request",headers: { "Content-type": "application/x-www-form-urlencoded" },})
.then((response) => response.json())
.then((responseJson) => {
var message = "";
if (responseJson.result === true) {
message =
"Your request for the quote has been made. You will recieve a quote in the quotes tab shortly.";
} else {
message =
"There was an error while send the request. Please try again in a short while.";
}
});
}
我也尝试过做
while(user === null){
retrieveData();
}
但这只会使我的应用崩溃。
解决方法
在调用retrieveData函数时,还必须使用异步/等待。 我已经修改了您的代码。现在它可以正常工作了
const [user,setUser] = useState(null)
async function getQuote() {
var retrieveData = async () => {
try {
const value = await AsyncStorage.getItem("user");
const data = JSON.parse(value);
setUser(data.user.email);
} catch (error) {}
};
await retrieveData();
fetch("http://localhost:3000/api/order/",{
method: "POST",body:
"product_id=" +
product._id +
"&user=" +
user +
"&quantity=" +
quote +
"&status=Request",headers: { "Content-type": "application/x-www-form-urlencoded" },})
.then((response) => response.json())
.then((responseJson) => {
var message = "";
if (responseJson.result === true) {
message =
"Your request for the quote has been made. You will recieve a quote in the quotes tab shortly.";
} else {
message =
"There was an error while send the request. Please try again in a short while.";
}
});
}