简体   繁体   English

useState 没有立即更新 state

[英]useState is not updating state immediately

here userlist is updating immediately what can be correct code for above logic I am trying fetch userlist from firestore than traversing that list to find user details from different collection这里userlist正在立即更新上面逻辑的正确代码我正在尝试从 firestore 获取 userlist 而不是遍历该列表以从不同的集合中查找用户详细信息

useEffect(() => {
    db.collection("following/" + Credens.uid + "/userFollowing")
      .get()
      .then((snapshot) => {
        followingList = snapshot.docs.map((value, ind) => value.data());
      })
      .then(() => {
        if (followingList.length > 0) {
          followingList.map((value, index) => {
            db.collection("Postss")
              .doc(value.useruid)
              .collection("MovieWatched")
              .get()
              .then((snaps) => {
                // let Detail = snap.data()
                let movieidList = snaps.docs.map(
                  (value) => value.data().postMovieId
                );

                if (movieidList.includes(MovieId) === true) {
                  setuserList((prev) => [...prev, value.useruid]);
                }
              });
          });
        }
      })
      .then(() => {
        console.log(userList);
        userList.map((value, index) => {
          db.collection("users")
            .doc(value)
            .get()
            .then((snapshot) => {
              setfriendsWatchedData((prev) => [
                ...prev,
                {
                  usersID: value,
                  userData: snapshot.data(),
                },
              ]);
            });
        });
      });

    // return () => {
    //     cleanup
    // }
  }, []);

To be sure the state did change, you can use the useEffect() to monitor the changing of that state like:为确保 state 确实发生了变化,您可以使用useEffect()来监视 state 的变化,例如:

useEffect(() => { 
  if (userList) {
  // userList.map....
  } 
}, [userList])

Additional conditions can be specified in the if statement.可以在 if 语句中指定其他条件。 The hook will run whenever the state changes.只要 state 发生变化,该挂钩就会运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM