一次又一次地将帖子发送到我的 redux 状态。 / Redux 工具包

问题描述 投票:0回答:1

我正在开发一个具有多个路由的项目,例如 /profile /admin /home 我正在个人资料页面中使用 Redux Toolkit 查询从后端获取帖子并成功获取帖子,但是当我转到另一个页面并返回个人资料并再次发送各州的帖子时

import { Link, useLocation } from "react-router-dom";
import Tweets from "../components/Tweets";
import { FaEdit } from "react-icons/fa";
import { useGetUserDetailsQuery } from "../slices/userApiSlice";
import ProfileRightBar from "../components/ProfileRightBar";
import { toast } from "react-toastify";
import Spinner from "../components/Spinner";
import { useEffect, useState, useRef } from "react";
import { useGetUserPostsQuery } from "../slices/postApiSlice";
import { useDispatch, useSelector } from "react-redux";
import { updateUserPosts } from "../slices/postSlice";

const ProfileScreen = () => {
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);

  const lastPostRef = useRef();
  const location = useLocation();
  const dispatch = useDispatch();
  const username = location.pathname.split("/")[2];


  const { data: posts, isFetching } = useGetUserPostsQuery();

  const { userPosts } = useSelector((state) => state.posts);

  useEffect(() => {
    toast.error(error?.data?.message);
  }, [error]);

  useEffect(() => {
    if (posts) {
      if (posts.length === 0) {
        setHasMore(false);
      } else {
        dispatch(updateUserPosts(posts));
      }
    }
  }, [posts]);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && !isFetching && hasMore) {
          // Fetch more posts when last post is intersecting
          setPage((prevPage) => prevPage + 1);
        }
      },
      { threshold: 1 }
    );

    if (lastPostRef.current) {
      observer.observe(lastPostRef.current);
    }

    // Cleanup the observer
    return () => observer.disconnect();
  }, [isFetching]);

  if (isLoading) {
    return <Spinner />;
  } else if (error) {
    return null;
  } else {
    return (
      <div className="w-full h-screen overflow-scroll">
        <div className="flex">
          <div className="border-r border-lightgray flex-[0.7]  h-screen overflow-auto">
            <Tweets posts={userPosts} />
            <div ref={lastPostRef}></div>
          </div>
        </div>
      </div>
    );
  }
};

export default ProfileScreen;

主要问题是当我回到个人资料页面时,它再次在我的数组中发送相同的帖子

reactjs redux react-redux react-router redux-toolkit
1个回答
0
投票

这就是效果的运行方式。当您返回页面时,看看会发生什么情况:组件再次挂载并再次进行服务器调用。服务器调用

dispatch(updateUserPosts(posts))
再次运行后。

我想在

updateUserPosts
中,您正在附加通过的帖子。理想情况下,您应该仅在帖子不存在时添加它们。您可以使用
filter()
Set
来获取独特的元素。

© www.soinside.com 2019 - 2024. All rights reserved.