javascript - 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 个帖子,仅此而已。
有什么帮助吗?
解决方案
推荐阅读
- rust - 为什么在为类型别名编写 impl 时会出现错误“无法为定义类型的 crate 之外的类型定义固有的 `impl`”?
- kubernetes - kubernetes:虽然 pod 健康,但服务无法访问
- angularjs - 如何将我的 anular js 前端连接到在两个快速服务器上运行的两个套接字不同连接
- php - 带有参数和类型的soap客户端调用函数
- android - 清单合并失败(使用房间)
- python - 如何计算每条记录中的单词并在最佳时间将其存储在单词和键级别?
- java - 示例 keycloak spring-boot 应用程序无法找到 bean KeycloakSpringBootConfigResolver
- r - 如何在 GGparcoord R 的平行坐标图中添加刻度?
- perl - 在 perl 中添加到哈希时遇到问题
- go - 使用 Go Olivere/elastic 过滤 value1 == value2 的 Elasticsearch 查询