如何在对象字面量中调用无返回值(void)函数?
解决对象字面量中调用无返回值函数的问题
你的核心问题是:定义对象字面量时直接执行了所有处理函数,而非根据type触发对应函数。
问题分析
你当前的对象字面量写法里,每个属性值都是handlePage()、handleAllLeft()这种函数执行的结果——这意味着在创建obj的瞬间,所有五个处理函数都会被调用一遍,不管传入的type是什么。而因为setCurrentPage是无返回值的void函数,这些属性最终的值都是undefined,后续return obj[type] || null自然起不到筛选执行的作用。
解决方案
把对象里的属性值改为函数本身(引用),而不是函数执行的结果。然后根据传入的type从对象中取出对应的函数,再调用它。
修改后的代码
const renderPagination = () => { const pageNumbers = []; for (let i = 1; i <= Math.ceil(data?.length / dataPerPage); i++) { pageNumbers.push(i); } const handlePageChange = (number, type) => { const handlePage = () => setCurrentPage(number); const handleAllLeft = () => setCurrentPage(1); const maxPage = Math.ceil(data?.length / dataPerPage); const handleAllRight = () => setCurrentPage(maxPage); const handleLeft = () => { setCurrentPage(currentPage === 1 ? 1 : currentPage - 1); }; const handleRight = () => { setCurrentPage(currentPage === maxPage ? maxPage : currentPage + 1); }; // 存储函数引用,而非执行结果 const actionMap = { "page": handlePage, "all-left": handleAllLeft, "all-right": handleAllRight, "left": handleLeft, "right": handleRight }; // 根据type获取函数并执行 const targetAction = actionMap[type]; if (targetAction) { targetAction(); } }; // 补充renderPagination的返回逻辑(比如渲染分页元素) };
额外优化点
- 提前计算
maxPage,避免多次重复调用Math.ceil(data?.length / dataPerPage),提升性能 - 把
handleLeft和handleRight里的if-else改成三元表达式,简化代码逻辑
内容的提问来源于stack exchange,提问作者rlevec
相关产品推荐
相关产品推荐

