You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用React Hook实现API返回节假日列表的名称搜索功能

React Hook 实现节假日搜索+点击跳转详情方案

你只需要修改现有代码的4处核心逻辑即可完成需求,以下是具体修改点和完整可运行代码:

需要修改的核心点

  • 修复原代码中搜索过滤逻辑的错误:原代码直接对holiday对象调用toLowerCase方法,应该取节假日名称字段holiday.name进行匹配
  • 搜索输入时自动重置页码到第一页:避免搜索结果总页数小于当前页码时出现空白列表
  • 修正分页组件的总计数:原分页总条数用的是全量节假日列表长度,搜索后要改为匹配后的结果长度,保证分页显示正确
  • 给表格行添加点击跳转逻辑:配合useHistory跳转到对应节假日详情页,路由可根据实际业务调整

修改后完整代码

import React, { useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import axios from 'axios';
import { Table, TablePagination } from 'react-bootstrap'; // 可根据你实际使用的UI库调整
import { FaSearch } from 'react-icons/fa';

const AddHolidayDateForm = () => {
    const history = useHistory();
    const [holidays, setHolidays] = useState([]);
    const [searchTerm, setSearchTerm] = useState("");
    const [page, setPage] = useState(0);
    const [rowsPerPage, setRowsPerPage] = useState(10);

    useEffect(() => {
        loadHoliday();
    }, []);

    const loadHoliday = async () => {     
        const res = await axios.post(`你的节假日接口地址`, {});  
        setHolidays(res.data.reverse());
    };

    const handleChangePage = (event, newPage) => {
        setPage(newPage);
    };

    const handleChangeRowsPerPage = event => {
        setRowsPerPage(parseInt(event.target.value, 10));
        setPage(0);
    };
   
    const handleChangeSearch = event => {
        setSearchTerm(event.target.value);
        // 搜索时自动重置到第一页
        setPage(0);
    };

    // 修复后的过滤逻辑,按名称模糊匹配
    const results = !searchTerm
        ? holidays
        : holidays.filter(
            holiday => holiday?.name?.toLowerCase().includes(searchTerm.toLocaleLowerCase())
        );

    // 跳转详情页方法,路由可根据实际业务调整
    const goToDetail = (holidayId) => {
        history.push(`/holiday/detail/${holidayId}`);
    };

    return (
        <div className="container">
            <div className="py-4">
                <div className="ui search">
                    <div className="float-left mb-3">
                        <input type="text"
                            placeholder="输入节假日名称搜索"
                            className="mr-sm-2"
                            value={searchTerm}
                            onChange={handleChangeSearch}
                        />
                        <FaSearch />
                    </div>
                </div>            
                <Table responsive>
                    <thead className="thead-dark">
                        <tr>
                            <th scope="col">#</th>
                            <th scope="col">名称</th>
                            <th scope="col">开始时间</th>
                            <th scope="col">结束时间</th>
                        </tr>
                    </thead>
                    <tbody>
                        {results
                                .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                                .map((holiday, index) => {
                                    return (
                                        // 新增点击事件和可点击的鼠标样式
                                        <tr 
                                            key={holiday.id} 
                                            onClick={() => goToDetail(holiday.id)}
                                            style={{cursor: 'pointer'}}
                                        >
                                            <th scope="row">{index + 1}</th>                                         
                                            <td>{holiday.name}</td>
                                            <td>{holiday.startTime}</td>
                                            <td>{holiday.endTime}</td>
                                        </tr>
                                    )
                                })                         
                        }
                        {/* 新增无匹配结果提示 */}
                        {results.length === 0 && (
                            <tr>
                                <td colSpan={4} className="text-center">暂无匹配的节假日</td>
                            </tr>
                        )}
                    </tbody>
                </Table>             
            </div>
            <div className="d-flex justify-content-center">
                <TablePagination
                    rowsPerPageOptions={[5, 10, 25]}
                    component="div"
                    {/* 分页总条数改为搜索结果长度 */}
                    count={results.length}
                    rowsPerPage={rowsPerPage}
                    page={page}
                    onChangePage={handleChangePage}
                    onChangeRowsPerPage={handleChangeRowsPerPage}
                />
            </div>
        </div>
    );
}
export default AddHolidayDateForm;

可选优化(数据量大时建议添加)

如果你的节假日列表超过1000条,可以给搜索输入加防抖逻辑,避免每输入一个字符就触发一次过滤,提升性能:

import { useDebounce } from 'react-use'; // 也可以自己手动实现防抖函数

// 替换原来的搜索相关逻辑,加200ms防抖
const [searchTerm, setSearchTerm] = useState("");
const [debouncedTerm, setDebouncedTerm] = useState("");

useDebounce(() => {
    setDebouncedTerm(searchTerm);
}, 200, [searchTerm]);

// 过滤用防抖后的debouncedTerm代替searchTerm
const results = !debouncedTerm
    ? holidays
    : holidays.filter(
        holiday => holiday?.name?.toLowerCase().includes(debouncedTerm.toLocaleLowerCase())
    );

内容的提问来源于stack exchange,提问作者efnan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 20:15:04