我做了一个非常简单的自定义无限滚动钩子,它根据传递给它的服务从多个分页的端点获取数据。
它与非参数化方法完美配合,但是当我将参数传递给它的function.call()
时,它永远不会真正将其传递给服务。
export const Details = (props) => {
const theme = useTheme();
console.log('component')
console.log(props.route.params.id);
const [comments, fetchMore] = fetchMoreItems(PAGINATED_ENDPOINTS.COMMENT, props.route.params.id);
//...
import { useCallback, useState, useEffect } from 'react';
import Seed from '../services/Seed.service';
export const PAGINATED_ENDPOINTS = {
SEED: Seed.fetchNextPage,
COMMENT: Seed.getComments,
NOTIFICATION: Notification.fetchNextPage
}
export function fetchMoreItems(itemFetchServiceMethod, params) {
console.log('hook');
console.log(params);
const [page, setPage] = useState(1);
const [shouldFetch, setShouldFetch] = useState(true);
const [items, setItems] = useState([]);
const fetchMore = useCallback(() => setShouldFetch(true), []);
useEffect(
() => {
if (!shouldFetch) {
return;
}
const fetch = async () => {
let newItems;
if (params) {
console.log('fetch');
console.log(params);
newItems = await itemFetchServiceMethod.call(params);
} else {
newItems = await itemFetchServiceMethod.call();
}
setShouldFetch(false);
setItems(oldItems => [...oldItems, ...newItems]);
setPage(page + 1);
};
fetch();
},
[page, shouldFetch],
);
return [items, fetchMore];
}
async getComments(seedId) {
console.log('service')
console.log(seedId);
try {
// ...
[Wed Sep 23 2020 12:50:48.710] LOG component
[Wed Sep 23 2020 12:50:48.730] LOG 5f64185f692b8b28b9a96029
[Wed Sep 23 2020 12:50:48.750] LOG hook
[Wed Sep 23 2020 12:50:48.790] LOG 5f64185f692b8b28b9a96029
[Wed Sep 23 2020 12:50:48.859] LOG fetch
[Wed Sep 23 2020 12:50:48.867] LOG 5f64185f692b8b28b9a96029
[Wed Sep 23 2020 12:50:48.868] LOG service
[Wed Sep 23 2020 12:50:48.869] LOG undefined