React Native 为什么我的数组过滤器在应该有多个匹配项的情况下返回一个空列表

ijxebb2r  于 2023-02-13  发布在  React
关注(0)|答案(1)|浏览(120)

我的数据存储在两个单独的表中;"posts"和"profiles"。每个User对象都来自"profiles"表,但也有一个列表posts,它不是"profiles"中的列。正因为如此,我需要先获取帖子,然后是它们对应的用户,然后根据"uid"将每个帖子添加到他们的User对象中。我下面的函数适用于大多数情况,但每个用户都有一个空的posts列表,即使在应该有柱的时候。

const [posts, setPosts] = useState<Array<Post>>([]);
  const [profiles, setProfiles] = useState<Array<User>>([]);

  useEffect(() => {
    async function fetchData() {
      const { data: postsData } = await supabase.from("posts").select("*");

      const postUids = postsData!.map((post) => post.uid);

      const { data: profilesData } = await supabase
        .from("profiles")
        .select("*")
        .in("uid", postUids);

      setPosts(postsData!.map((post) => new Post(post)));
      const profiles = profilesData!.map((userData: any) => {
        const userPosts: Array<Post> = posts.filter(
          (post) => post.uid === userData.uid
        );
        console.log("User posts: " + userPosts);
        const user = new User({ ...userData, posts: userPosts });
        // user.posts = [...user.posts, ...userPosts];
        console.log(user);
        return user;
      });
      setProfiles((prevUsers) => [...prevUsers, ...profiles]);
      console.log(profiles);
    }

    fetchData();
  }, []);

  console.log(posts);
  console.log(profiles);

postsData示例:

[{
   "caption":"Caption",
   "date":"1669244422569",
   "imageUrls":[
      "https://cdn.pixabay.com/photo/2020/05/04/16/05/mckenzie-river-5129717__480.jpg"
   ],
   "location":{
      "latitude":150,
      "locationInfo":"City, State",
      "longitude":-150
   },
   "postId":"1669244407166",
   "uid":"daf6b8be-7cd0-4341-89d7-07879b207087"
}]

发布对象:

export default class Post {
  imageUrls: Array<string>;
  postId: string;
  uid: string;
  caption: string;
  location: Location;
  date: number;

  constructor(post: any) {
    this.imageUrls = post.imageUrls;
    this.postId = post.postId;
    this.uid = post.uid;
    this.caption = post.caption;
    this.location = post.location;
    this.date = post.date;
  }
}

配置文件示例数据:

{
   "blockedUsers":[],
   "displayName":"name",
"photoURL":"https://cdn.pixabay.com/photo/2020/05/04/16/05/mckenzie-river-5129717__480.jpg",
   "uid":"daf6b8be-7cd0-4341-89d7-07879b207087",
   "verified":false
}

用户对象:

export default class User {
  uid: string;
  blockedUsers: Array<string>;
  posts: Array<Post>;
  photoURL: string;
  displayName: string;
  verified: boolean;

  constructor(user: any) {
    this.uid = user.uid;
    this.blockedUsers = user.blockedUsers;
    this.posts = user.posts;
    this.photoURL = user.photoURL;
    this.displayName = user.displayName;
    this.verified = user.verified;
  }
}
mec1mxoz

mec1mxoz1#

不完全确定为什么你没有得到任何帖子数据,可能是由于你的RLS是如何配置的,但是有一个更好的方法来查询你的数据。
可以同时查询postsprofiles,如下所示:

const { data, error } = await supabase.from("profiles").select("*, posts(*)");

这样,您就不必执行另一个查询来分别检索概要文件,也不必循环检索到的对象来修改它们。

相关问题