ReactJS对接外部API的搜索栏问题:变量未使用与搜索失效
React + AgGrid + OpenLibrary API:解决搜索未关联及变量未使用问题
问题1:'search' is assigned a value but never used 错误
这个变量是实现搜索功能的核心,必须保留。之前的代码仅更新了它的值,但未将其用于过滤数据或发起API请求,因此触发ESLint报错。我们需要利用该状态关联搜索逻辑。
问题2:搜索栏未与AgGrid关联
需要将搜索关键词与表格数据绑定,以下提供两种常用实现方案:
方案1:前端过滤已有数据(适合小数据量)
无需重新请求API,直接在前端过滤已加载的全量图书数据,响应速度更快:
import React, { useState, useEffect } from "react"; import { AgGridReact } from "ag-grid-react"; import "ag-grid-community/dist/styles/ag-grid.css"; import "ag-grid-community/dist/styles/ag-theme-balham.css"; import "bootstrap/dist/css/bootstrap.min.css"; import {Button, Badge} from "reactstrap"; export default function App() { const [originalRowData, setOriginalRowData] = useState([]); // 存储全量原始数据 const [rowData, setRowData] = useState([]); // 存储过滤后的数据 const [search, setSearch] = useState(""); const columns = [ { headerName: "Title", field: "title" }, { headerName: "Author", field: "author" }, { headerName: "Edition Count", field: "editionCount" }, { headerName: "Book ID", field: "id" } ]; // 加载初始分类数据 useEffect(() => { fetch("https://openlibrary.org/subjects/drama.json?published_in=2000") .then(res => res.json()) .then(data => data.works) .then(works => works.map(book => ({ title: book.title, author: book.authors[0].name, editionCount: book.edition_count, id: book.cover_id })) ) .then(books => { setOriginalRowData(books); setRowData(books); }); }, []); // 根据搜索关键词实时过滤数据 useEffect(() => { if (!search) { setRowData(originalRowData); return; } const filtered = originalRowData.filter(book => book.title.toLowerCase().includes(search.toLowerCase()) || book.author.toLowerCase().includes(search.toLowerCase()) ); setRowData(filtered); }, [search, originalRowData]); return ( <div className="container"> <h1>Book Catalogue</h1> <SearchBar onSubmit={setSearch} /> <p> <Badge color="success">{rowData.length}</Badge> Books published in 2000 in the Drama category </p> <div className="ag-theme-balham" style={{ height: "300px", width: "800px" }} > <AgGridReact columnDefs={columns} rowData={rowData} pagination={true} paginationPageSize={7} /> </div> <Button color="info" size="sm" className="mt-3" href="https://openlibrary.org/developers/api" target="_blank" > Go to Open Library API </Button> </div> ) }; function SearchBar(props) { const [innerSearch, setInnerSearch] = useState(""); return ( <div className="mb-3"> <input aria-labelledby="search-button" name="search" id="search" type="search" value={innerSearch} onChange={e => setInnerSearch(e.target.value)} placeholder="Search by title or author..." className="me-2" /> <button id="search-button" type="button" onClick={() => props.onSubmit(innerSearch)} className="btn btn-primary" > Search </button> </div> ); }
修改说明:
- 新增
originalRowData状态存储全量原始数据,避免重复请求API - 添加依赖
search的useEffect,关键词变化时自动过滤数据 - 修复reactstrap属性拼写错误:
colour改为美式拼写color - 优化搜索栏样式与占位符,提升用户体验
方案2:调用OpenLibrary搜索API(适合大数据量)
若图书数据量较大,前端过滤效率低,可直接调用OpenLibrary搜索接口获取精准匹配数据:
export default function App() { const [rowData, setRowData] = useState([]); const [search, setSearch] = useState(""); const columns = [ { headerName: "Title", field: "title" }, { headerName: "Author", field: "author" }, { headerName: "Edition Count", field: "editionCount" }, { headerName: "Book ID", field: "id" } ]; // 根据搜索关键词请求对应API useEffect(() => { const url = search ? `https://openlibrary.org/search.json?q=${encodeURIComponent(search)}&subject=drama&published_in=2000` : "https://openlibrary.org/subjects/drama.json?published_in=2000"; fetch(url) .then(res => res.json()) .then(data => { // 适配搜索接口与分类接口的不同返回结构 const works = search ? data.docs : data.works; return works.map(book => ({ title: book.title, author: search ? book.author_name?.[0] : book.authors[0].name, editionCount: book.edition_count, id: search ? book.cover_i : book.cover_id })); }) .then(books => setRowData(books)); }, [search]); // 其余代码同方案1... }
说明:
- OpenLibrary搜索接口(
/search.json)与分类接口返回结构不同,需做字段适配 - 使用
encodeURIComponent处理搜索关键词,避免特殊字符导致请求错误
参考学习方向
- AgGrid内置过滤:在列定义中添加
filter: true,可快速实现列级原生过滤,无需手动编写逻辑 - React+AgGrid状态管理:官方文档提供大量React集成示例,学习如何通过状态控制表格数据更新
- OpenLibrary API细节:熟悉不同接口的参数与返回结构,灵活实现多维度筛选需求
内容的提问来源于stack exchange,提问作者dangoqut132
相关产品推荐
相关产品推荐

