mongodb 如何使用useEffect()指定添加好友和取消好友按钮

sqougxex  于 2022-12-18  发布在  Go
关注(0)|答案(1)|浏览(122)

map函数和第一个if语句不起作用.如果所选用户的id已经存在于当前用户的朋友数组中,我想将friend设置为true.

const currentProfile = users.filter((user) => user._id === id)[0]; //the selected profile
const currentUser = useSelector((state) => state.currentUserReducer); // user logged in
useEffect(() => {
  if (currentUser) {
    // not working
    //currentUser?.result?.friends is an array of objects containing id of all friends added
    currentUser?.result?.friends.map((friends) => {
      //not working
      if (friends._id === currentProfile._id) {
        return setFriend(true);
      }
    });
  } else {
    return setFriend(false);
  }
}, [currentUser, currentProfile]);
dgsult0t

dgsult0t1#

尝试使用some这样的函数来检查朋友是否存在,而不是Map:

useEffect(() => {
  if (currentUser) {
    const selectedIdAlreadyPresent = currentUser.result?.friends?.some(f => f._id === currentProfile._id) || false;
    setFriend(selectedIdAlreadyPresent);
  }
}, [currentUser, currentProfile]);

相关问题