首页 > 解决方案 > React - 从上下文中获取分页数据

问题描述

我有当前的上下文

export function UserPostsProvider({ children }) {
  const [posts, dispatch] = useReducer(userPostsReducer, initialState);

  const addUserPosts = (userId, posts, unshift = false) => {
    dispatch(actionCreators.addUserPosts(userId, posts, unshift));
  };

  const getUserPosts = (userId, index = 0, limit = undefined) => {
    const _posts = posts[userId] ?? [];
    return _posts.slice(index, limit + index || undefined);
  };

  return (
    <UserPostsContext.Provider
      value={{
        addUserPosts,
        deleteUserPost,
        getUserPosts,
      }}
    >
      {children}
    </UserPostsContext.Provider>
  );
}

如您所见,我有一个方法“getUserPosts”,它接受两个参数“index”和“limit”。

我正在使用以下上下文:

export default function useFetchUserPosts(userData) {
  const isMounted = useIsMounted();

  const userPosts = useUserPosts();

  const cards = useCards();

  const posts = userPosts.getUserPosts(userData.id); // <--- HERE!
  const [isLoading, setIsLoading] = useState(!posts.length);
  const [error, serError] = useState(undefined);

  const startAfter = useRef(new Date()); 

  const getMorePosts = async (limit = 10) => {
     if (isFetching.current || !hasMoreToLoad.current || !isMounted()) {
           return;
     }

     isFetching.current = true;

     setIsLoading(true);

     try {
        const {
           posts: newPosts,
           hasMoreToLoad: newHasMoreToLoad,
           startAfter: newStartAfter,
        } = await getUserPosts(userData.id, startAfter.current, limit);

        // The component might be unmounted
        if (!isMounted()) return;

        hasMoreToLoad.current = newHasMoreToLoad;

        startAfter.current = newStartAfter;

        userPosts.addUserPosts(userData.id, newPosts);

        setIsLoading(false);

        isFetching.current = false;
     } catch(err) {
       setError(err);
     }         
  }
  
  ...
}

如何从上下文中获取正确的帖子分页部分?我的意思是,如果我只是在每次重新渲染时从上下文中获取前 10 个帖子,我将始终获得前 10 个帖子,仅此而已。

有什么帮助吗?

标签: javascriptreactjsreact-nativereact-reduxreact-hooks

解决方案


推荐阅读