【问题标题】:How do I use search in react?如何在反应中使用搜索?
【发布时间】:2021-11-04 09:15:44
【问题描述】:

我想在来自 API 的假期列表中按假期名称进行搜索。用户应该能够通过在 crud 表列表中看到它后单击它来选择具有她/他正在寻找的假期名称的行。我希望用户在整个列表中仅按名称查找他/她正在寻找的假期并访问其详细信息。我怎么能用反应钩子做到这一点?代码如下所示。


const AddHolidayDateForm = () => {

    let history = useHistory();
    const [holidays, setHolidays] = useState([])
   const [searchTerm, setSearchTerm] = React.useState("");

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

    const loadHoliday = async () => {     
        const res = await axios.post(`..`, {   });  
        
        setHolidays(res.data.reverse());
    };

    const [page, setPage] = React.useState(0);
    const [rowsPerPage, setRowsPerPage] = React.useState(10);
    const handleChangePage = (event, newPage) => {
        setPage(newPage);
    };

    const handleChangeRowsPerPage = event => {
        setRowsPerPage(parseInt(event.target.value, 10));
        setPage(0);
    };
   
     const handleChangeSearch = event => {
        setSearchTerm(event.target.value);
    };

    const results = !searchTerm
        ? holidays
        : holidays.filter(
            holiday => holiday && holiday.toLowerCase && holiday.toLowerCase().includes(searchTerm.toLocaleLowerCase())
        );


    return (
        <div className="container">
            <div className="py-4">
                <div className="ui search">
                    <div className="float-left mb-3">
                        <input type="text"
                            placeholder="search"
                            className="mr-sm-2"
                            value={searchTerm}
                            onChange={handleChangeSearch}
                        />
                        <FaSearch />
                    </div>
                </div>            
                <Table responsive>
                    <thead class="thead-dark">
                        <tr>
                            <th scope="col">#</th>
                           
                            <th scope="col">Name</th>
                            <th scope="col">Start Time</th>
                            <th scope="col">End Time</th>
                        </tr>
                    </thead>
                    <tbody>
                        {results
                                .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                                .map((holiday, index) => {
                                    return (
                                        <tr>
                                            <th scope="row">{index + 1}</th>                                         
                                            <td>{holiday.name}</td>
                                            <td>{holiday.startTime}</td>
                                            <td>{holiday.endTime}</td>
                                        </tr>                                    )
                                })                         
                        }

                    </tbody>
                </Table>             
            </div>
            <div className="col-sm-6">
               </div>
            <div className="d-flex justify-content-center">
                <TablePagination
                    rowsPerPageOptions={[5, 10, 25]}
                    component="div"
                    count={holidays.length}
                    rowsPerPage={rowsPerPage}
                    page={page}
                    onChangePage={handleChangePage}
                    onChangeRowsPerPage={handleChangeRowsPerPage}
                />
            </div>
        </div>
    );
}
export default AddHolidayDateForm;

【问题讨论】:

    标签: javascript reactjs react-hooks react-router react-bootstrap-table


    【解决方案1】:

    我看到的第一件事是results 不是状态变量。在反应中,如果你想渲染一个变量,你必须将它作为一个状态变量来管理。

    因此,以这种方式更改您的代码:

    const AddHolidayDateForm = () => {
    
        let history = useHistory();
        const [holidays, setHolidays] = useState([])
       const [searchTerm, setSearchTerm] = React.useState("");
       const [res, setRes] = useState([]);  //<-- state to render
    
        useEffect(() => {
            loadHoliday();
        }, []);
    
        useEffect(() => {  //<-- every time holidays or searchTerm change, filter results
           const results = !searchTerm
            ? holidays
            : holidays.filter(
                holiday => holiday && holiday.toLowerCase && holiday.toLowerCase().includes(searchTerm.toLocaleLowerCase())
            );
            setRes(results);
        }, [holidays, searchTerm]);
    
        const loadHoliday = async () => {     
            const res = await axios.post(`..`, {   });  
            
            setHolidays(res.data.reverse());
        };
    
        const [page, setPage] = React.useState(0);
        const [rowsPerPage, setRowsPerPage] = React.useState(10);
        const handleChangePage = (event, newPage) => {
            setPage(newPage);
        };
    
        const handleChangeRowsPerPage = event => {
            setRowsPerPage(parseInt(event.target.value, 10));
            setPage(0);
        };
       
         const handleChangeSearch = event => {
            setSearchTerm(event.target.value);
        };
    
    
        return (
            <div className="container">
                <div className="py-4">
                    <div className="ui search">
                        <div className="float-left mb-3">
                            <input type="text"
                                placeholder="search"
                                className="mr-sm-2"
                                value={searchTerm}
                                onChange={handleChangeSearch}
                            />
                            <FaSearch />
                        </div>
                    </div>            
                    <Table responsive>
                        <thead class="thead-dark">
                            <tr>
                                <th scope="col">#</th>
                               
                                <th scope="col">Name</th>
                                <th scope="col">Start Time</th>
                                <th scope="col">End Time</th>
                            </tr>
                        </thead>
                        <tbody>
                            {res   //<-- here use res state and not results
                                    .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                                    .map((holiday, index) => {
                                        return (
                                            <tr>
                                                <th scope="row">{index + 1}</th>                                         
                                                <td>{holiday.name}</td>
                                                <td>{holiday.startTime}</td>
                                                <td>{holiday.endTime}</td>
                                            </tr>                                    )
                                    })                         
                            }
    
                        </tbody>
                    </Table>             
                </div>
                <div className="col-sm-6">
                   </div>
                <div className="d-flex justify-content-center">
                    <TablePagination
                        rowsPerPageOptions={[5, 10, 25]}
                        component="div"
                        count={holidays.length}
                        rowsPerPage={rowsPerPage}
                        page={page}
                        onChangePage={handleChangePage}
                        onChangeRowsPerPage={handleChangeRowsPerPage}
                    />
                </div>
            </div>
        );
    }
    export default AddHolidayDateForm;
    

    【讨论】:

    • 感谢您的回答。我按你说的改了。它没有显示我在表格列表的搜索部分中输入的单词。每次我在搜索部分输入时,列表都是空的。
    猜你喜欢
    • 1970-01-01
    • 2021-08-09
    • 2021-11-21
    • 2018-05-15
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    相关资源
    最近更新 更多