gpt4 book ai didi

javascript - 从 React 自定义 Hook 调用的函数返回 'is not a function'

转载 作者:行者123 更新时间:2023-12-02 01:48:16 25 4
gpt4 key购买 nike

当我尝试从我的自定义 Hook 调用一个函数时,我在屏幕加载时收到一条错误消息,提示“handleLazyLoad”不是一个函数。我不确定为什么 React 无法弄清楚 handleLazyLoad 是一个函数,我想我可能会导出它或错误地调用它。

自定义钩子(Hook):

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;

最佳答案

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

return [totalShownInvoices, handleLazyLoad];

到:

return {totalShownInvoices, handleLazyLoad};

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

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

关于javascript - 从 React 自定义 Hook 调用的函数返回 'is not a function',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70651034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com