You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React数组筛选返回空列表:为User关联Post失败

问题分析与解决

你的代码里用户的posts列表为空,核心原因是useState的更新是异步的:调用setPosts(postsData!.map(...))后,posts状态并不会立刻更新为新的帖子数组,此时你用posts.filter(...)过滤的还是初始的空数组,自然拿不到匹配的帖子。

另外还有个潜在问题:postsData里的date是字符串类型,但Post类定义的date是number类型,需要在构造函数里做类型转换,避免类型不匹配。

修复后的代码

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

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

    // 先把postsData转换为Post实例,存在临时变量里,不依赖useState的异步更新
    const convertedPosts = postsData.map(post => new Post(post));
    const postUids = convertedPosts.map(post => post.uid);

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

    // 用临时变量convertedPosts过滤用户对应的帖子
    const profiles = profilesData.map((userData: any) => {
      const userPosts = convertedPosts.filter(post => post.uid === userData.uid);
      return new User({ ...userData, posts: userPosts });
    });

    // 最后统一更新状态
    setPosts(convertedPosts);
    setProfiles(profiles);
  }

  fetchData();
}, []);

补充修复:Post类的date类型转换

修改Post类的构造函数,把字符串类型的date转为number:

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;
    // 将字符串date转为number类型
    this.date = Number(post.date);
  }
}

内容的提问来源于stack exchange,提问作者Globe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 13:40:59