如何处理两个 useEffect 钩子,其中一个 useEffect 依赖项影响另一个 useEffect 依赖项?

时间:2021-06-09 01:50:02

标签: reactjs react-hooks use-effect react-state-management

所以我正在开发一个具有无限滚动和排序/过滤功能的网站。问题是,当更改 sortBy 方法时,我需要重置无限滚动页面的分页偏移量。

这是组件的代码:

function Listings({ setListingCount, sortBy }) {
  const [listings, setListings] = useState([]);
  const [isInitialLoading, setIsInitialLoading] = useState(true);
  const [isLoading, setIsLoading] = useState(true);
  const [apiError, setApiError] = useState(false);
  const [offset, setOffset] = useState(0);
  const [hasMore, setHasMore] = useState(true);
  const limit = 12;

  const observer = useRef();
  const lastListingElementRef = useCallback((node) => {
    if (isLoading) {
      return;
    }

    if (observer.current) {
      observer.current.disconnect();
    }

    observer.current = new IntersectionObserver((entries) => 
  {
      if (entries[0].isIntersecting && hasMore) {
        setOffset((prevOffset) => prevOffset + limit);
      }
    });
    if (node) {
      observer.current.observe(node);
    }
  }, [isLoading, hasMore]);

  function resetListings() {
    setListings([]);
    setIsInitialLoading(true);
    setApiError(false);
    setOffset(0);
    setHasMore(true);
    setListingCount('0');
  }

  useEffect(() => {
    resetListings();
  }, [sortBy]);

  useEffect(async () => {
    try {
      setIsLoading(true);
      const response = await axios.get(
        'listings',
        {
          params: {
            offset,
            limit,
            sb: sortBy
          }
        }
      );
      setListings((prevListingIds) => [
        ...new Set(
          [...prevListingIds, ...response.data.rows]
        )
      ]);
      setListingCount(response.data.count);
      setHasMore(response.data.rows.length > 0);
      setIsLoading(false);
      setIsInitialLoading(false);
    } catch (error) {
      setApiError(true);
      setIsLoading(false);
      setIsInitialLoading(false);
    }
  }, [sortBy, offset]);

  return();
}

第一个 useEffect 用于在 sortBy 更改时重置状态。第二个 useEffect 用于在偏移更改或 sortBy 更改时加载更多数据。当前发生的情况是当用户在偏移量不为 0(假设为 12)时更改 sortBy,然后第二个 useEffect 在第一个 {{1} 之前使用 offset = 12 发出 get 请求}} 能够将偏移量重置回 0。但是一旦偏移量被第一个 useEffect 重置为 0,另一个获取请求是使用 useEffect 发出的,所以现在它呈现 24 个列表而不是 12 个,而且顺序错误。

我应该如何处理不能保证按我期望的顺序运行的 offset = 0?有没有另一种方法来实现这个逻辑?感谢您提供的任何帮助!

0 个答案:

没有答案