自定义钩子不将参数传递给存储为对象的服务方法

时间:2020-09-23 15:57:57

标签: javascript reactjs react-hooks

问题

我做了一个非常简单的自定义无限滚动钩子,它根据传递给它的服务从多个分页的端点获取数据。 它与非参数化方法完美配合,但是当我将参数传递给它的function.call()时,它永远不会真正将其传递给服务。

问题

  1. 如何传递确实能传递给服务的参数?
  2. 一个附带的问题,是否有更好的方法来“存储”我的分页端点以供我的钩子使用?

代码

  • 具有自定义钩子调用的组件

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);
//...
  • infiniteScroll.hook.js
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];
}
  • Seed.service.js
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

0 个答案:

没有答案