【问题标题】:Function called from a react custom hook returns 'is not a function'从反应自定义挂钩调用的函数返回“不是函数”
【发布时间】:2022-01-10 10:36:23
【问题描述】:

当我尝试从我的自定义钩子中调用一个函数时,当屏幕加载说“handleLazyLoad”不是一个函数时,我得到一个错误。我不知道为什么 React 无法确定 handleLazyLoad 是一个函数,我想我可能会导出它或错误地调用它。

自定义钩子:

import { useState } from 'react';

const useLoadInvoices = (initialPageValue, totalInvoices) => {
  const [currentPage, setCurrentPage] = useState(initialPageValue);

  const pageSize = 30;

  const handleLazyLoad = () => {
    if (currentPage * pageSize < totalInvoices) setCurrentPage(currentPage + 1);
  };

  const totalShownInvoices = currentPage * pageSize > totalInvoices ? totalInvoices : currentPage * pageSize;

  return [totalShownInvoices, handleLazyLoad];
};

export default useLoadInvoices;

发票屏幕组件:

import React from 'react';
import useLazyLoad from './hooks/useLazyLoad';

const InvoicesScreen = () => {
  const [invoices, setInvoices] = useState(null);
  const [totalInvoices, setTotalInvoices] = useState(null);
  const [handleLazyLoad, totalShownInvoices] = useLoadInvoices(1, totalInvoices);

  handleLazyLoad();

  return (
    <AccountPageList
      type="invoices"
      handleLazyLoad={() => handleLazyLoad()}
      start={1}
      finish={totalShownInvoices}
      total={totalInvoices}
      items={invoices}
    />
  );
};

export default InvoicesScreen;

【问题讨论】:

  • 错字:你的数组中两个元素的顺序颠倒了。
  • 离题:handleLazyLoad={handleLazyLoad} 更好
  • 不错,我没有意识到顺序很重要,也没有考虑切换它
  • 当它是一个数组时,如果你有返回一个对象,它就不会
  • @Thomas,视情况而定,有时您不希望参数自动传递给函数

标签: javascript reactjs react-hooks


【解决方案1】:

您从自定义钩子返回一个数组,因此在解构自定义钩子时,顺序很重要。为避免此类问题,您可以在自定义挂钩中更改此部分:

return [totalShownInvoices, handleLazyLoad];

到:

return {totalShownInvoices, handleLazyLoad};

然后你可以如下解构它,顺序无关紧要:

const {handleLazyLoad, totalShownInvoices} = useLoadInvoices(
    1,
    totalInvoices,
  );

【讨论】:

    【解决方案2】:

    对数组进行解构时,顺序很重要 试试

    const [totalShownInvoices,handleLazyLoad] = useLoadInvoices(
        1,
        totalInvoices,
      );
    

    【讨论】:

      猜你喜欢
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 2020-08-01
      • 1970-01-01
      • 2022-12-18
      • 1970-01-01
      • 1970-01-01
      • 2018-02-21
      相关资源
      最近更新 更多