React Native 如何避免第一次重新加载时数组useState为空?

mutmk8jj  于 2023-04-22  发布在  React
关注(0)|答案(1)|浏览(125)

每次我重新加载应用程序时,我都会得到空的useSate Array,但是当我通过vscode保存或刷新时,只有我才能看到结果。

React Native代码

useEffect(() => {
    (async () => {
      if (users.length > 0) return;
      const q = query(
        collection(db, "favoritFreelancer"),
        where("cid", "==", userUid)
      );
      const querySnapshot = await getDocs(q);
      const userArray = [];
      querySnapshot.forEach(async (favUser) => {
        onSnapshot(doc(db, "users", favUser.data().lancerID), (user) => {
          userArray.push(user.data());
        });
        setUsers(userArray);
      });
    })();
  }, []);

这个板条箱无限循环

useEffect(() => {
    (async () => {
      if (users.length > 0) return;
      const q = query(
        collection(db, "favoritFreelancer"),
        where("cid", "==", userUid)
      );
      const querySnapshot = await getDocs(q);
      const userArray = [];
      querySnapshot.forEach(async (favUser) => {
        onSnapshot(doc(db, "users", favUser.data().lancerID), (user) => {
          userArray.push(user.data());
        });
        setUsers(userArray);
      });
    })();
  }, [users]);

Map阵列状态

<ScrollView style={{ flex: 1 }} className="flex-col w-full">
        {users.map((user) =>
          searchText === "" ? (
            <FreelancerCard
              key={user.uid}
              fullname={user.fullname}
              experience={user.experience}
              stars={user.stars}
              jobs={user.jobs}
              status={user.status}
              categories={user.category}
              contact={user.contact}
              imgUrl={user.profilePic}
            />
          ) : fullname.toLowerCase().includes(searchText.toLowerCase()) ? (
            <FreelancerCard
              key={user.uid}
              fullname={user.fullname}
              experience={user.experience}
              stars={user.stars}
              jobs={user.jobs}
              status={user.status}
              categories={user.category}
              contact={user.contact}
              imgUrl={user.profilePic}
            />
          ) : null
        )}
      </ScrollView>

Firebase集合****用户集合

收藏Freelancer收藏

当重新加载应用程序=〉我尝试

当我保存代码=〉我希望

=〉这需要在我的应用程序重新加载时显示

6l7fqoea

6l7fqoea1#

试试这个

const [users, setUsers] = useState([]);
useEffect(() => {
  getUserData();
},[])

const getUserData = async () => {
  if (users.length > 0) return;
  const q = query(
    collection(db, "favoritFreelancer"),
    where("cid", "==", userUid)
  );
  const querySnapshot = await getDocs(q);
}

querySnapshot.forEach(async (favUser) => {
    onSnapshot(doc(db, "users", favUser.data().lancerID), (user) => {
      // If the data is coming in a key value pair 
      setUsers([...users,user.data()]);
      // If the data is not coming in a key value pair
      setUsers([...users,{user.data()}]);
    });
});

相关问题