【发布时间】: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