我在我的 React Native 应用程序中将两个 Promise 链接在一起时遇到了很多麻烦。第一个 Promise 成功获取异步存储中的值并将其设置为状态。第二个 Promise 获取我从 Firebase 获得的数据,但取决于我从第一个 Promise 设置的状态。任何帮助将不胜感激。import React, { useState, useEffect } from "react";import { Text, StyleSheet, View } from "react-native";import firebase from "../../firebase/fbConfig";import AsyncStorage from "@react-native-async-storage/async-storage";let DB = firebase.firestore();function Questions(props) { const [productId, setProductId] = useState(""); const [question, setQuestion] = useState(""); const [reward, setReward] = useState(""); const getAsyncData = () => { AsyncStorage.getItem("key").then((value) => setProductId(value)) // works fine // }; const getDataFromFirebase = (productId) => { DB.collection("ads") .where("productId", "==", productId) .get() .then(function (querySnapshot) { querySnapshot.forEach(function (doc) { setQuestion(doc.data().question); setReward(doc.data().reward); }); }) .catch(function (error) { console.log("Error getting documents: ", error); }); // works fine // }; useEffect(() => { getAsyncData().then((productId) => getDataFromFirebase(productId)); // does not work // }); return ( <> <View style={styles.container}> </View> </> );}export default Questions;
1 回答
潇湘沐
TA贡献1816条经验 获得超6个赞
试试这个方法
useEffect(() => {
getAsyncData();
}, []);
const getAsyncData = async () => {
try {
const productId = await AsyncStorage.getItem("key");
getDataFromFirebase(productId);
} catch (error) {
console.log(error);
}
};
添加回答
举报
0/150
提交
取消