【发布时间】:2021-12-15 08:20:53
【问题描述】:
我正在实现一个钩子“useUserPosts”,它应该在我的应用程序的多个路由中使用。
由于我已经有一个上下文“PostsContext”,它会在数据更改时重新呈现我的卡片(totalLikes、totalComments、描述等),我决定避免创建另一个名为“UserPostsContext”的上下文,其目的是返回用户发布数组。
我知道,为什么不改用 PostsContext?...
答案是,在 PostsContext 中,为了避免性能问题,我存储了一个映射(键、值),以便在 O(1) 中获取/更新帖子动态数据,仅在我的组件中有用的东西(因此,它基本上用于同步卡片)
在 React 中创建处理全局状态而不使用 Context API 或 Redux 的钩子是否可能/一种常见做法?
我的意思是,像
// Global State Hook
const useUserPosts = (() => {
const [posts, setPosts] = useState({});
return ((userId) => [posts[id] ?? [], setPosts]);
})();
// Using the Global State Hook
function useFetchUserPosts(userId) {
const [posts, setPosts] = useUserPosts(userId);
const [loading, setLoading] = useState(!posts.length);
const [error, setError] = useState(undefined);
const cursor = useRef(new Date());
const hasMoreToLoad = useRef(false);
const isFirstFetch = useRef(true);
const getUserPosts = async () => {
// ...
}
return { posts, loading, error, getUserPosts };
}
注意:我这样做的目的是:
1. Reproduce some kind of cache
2. Synchronize the fetched data of each stack screen that is mounted in order to reduce backend costs
3. Synchronize user posts deletions
【问题讨论】:
标签: javascript reactjs react-native react-hooks