由于清理,反应/状态未更新

时间:2021-05-22 06:12:38

标签: reactjs

我有自定义挂钩,可为创建的帖子添加用户信息。如果我不添加清理,它会按预期工作。我创建新帖子,按帖子并将其添加到屏幕上,但使用 if(mounted.current)setState() 它不会更新,仅在刷新时更新。可能是什么问题,我该如何解决?

const AllPostsAssign = () => {
  const { userPosts, allUsers } = useData();
  const [posts, setPosts] = useState();
  const mounted = useRef(true);

  // map existing posts and add user object and post id into post object.
  useEffect(() => {
    const postsWithUsers = allUsers.map((y) => {
      const usersAssignedToPosts = userPosts.map((x) => {
        if (y.userId === x.data().userId) {
          const q = Object.assign(x.data(), { id: x.id });
          const z = Object.assign(q, { user: y });
          return z;
        }
      });
      return usersAssignedToPosts;
    });
    const noUndefined = postsWithUsers.flat().filter((post) => post);

// without mounted.current it works.
    if (noUndefined && mounted.current) setPosts(noUndefined);

    console.log(mounted.current);
    console.log(posts);

    return () => (mounted.current = false);
  }, [userPosts, allUsers]);

  // sort by time created and then reverse, so newest posts would be on top.
  posts &&
    posts.sort((a, b) => {
      return a.createdAt.seconds - b.createdAt.seconds;
    });
  posts && posts.reverse();
  return posts;
};

export default AllPostsAssign;

1 个答案:

答案 0 :(得分:1)

直接在您的 mounted 中声明您的 useEffect 支票,例如:

  useEffect(() => {
   let mounted = true;

    const postsWithUsers = allUsers.map((y) => {
      const usersAssignedToPosts = userPosts.map((x) => {
        if (y.userId === x.data().userId) {
          const q = Object.assign(x.data(), { id: x.id });
          const z = Object.assign(q, { user: y });
          return z;
        }
      });
      return usersAssignedToPosts;
    });
    const noUndefined = postsWithUsers.flat().filter((post) => post);

// without mounted.current it works.
    if (noUndefined && mounted) setPosts(noUndefined);

    console.log(mounted);
    console.log(posts);

    return () => (mounted = false);
  }, [userPosts, allUsers]);
相关问题