React新手求助:基于Hooks的搜索栏API调用与数据过滤故障
我是JavaScript和React领域的新手,正在学习Hooks,尝试为搜索栏调用API实现按标题过滤数据,但功能无法正常运行。我期望从指定URL获取数组格式的数据,通过搜索栏根据标题筛选内容,我的代码如下:
function Search() { const [searchTerm, setSearchTerm] = useState([]); const [text,setText] = useState([]); const getAPI = async() => { const response = await fetch("https://fakestoreapi.com/products") const data = await response.json() setText(data.Search) } useEffect( () => { getAPI() }, []) return <div> <input placeholder="searching" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)}/> </div> };
问题修复及完整实现
先给你修正后的可运行代码,再逐个拆解问题:
function Search() { // 搜索关键词初始化为空字符串(输入框存文本,不是数组) const [searchTerm, setSearchTerm] = useState(""); // 存储API返回的产品列表,初始化为空数组 const [products, setProducts] = useState([]); const getAPI = async() => { const response = await fetch("https://fakestoreapi.com/products"); const data = await response.json(); // 接口返回的直接是产品数组,没有Search属性 setProducts(data); } useEffect(() => { getAPI(); }, []); // 实现标题过滤逻辑:不区分大小写匹配搜索词 const filteredProducts = products.filter(product => product.title.toLowerCase().includes(searchTerm.toLowerCase()) ); return ( <div> <input placeholder="搜索商品标题" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} /> {/* 渲染过滤后的产品列表 */} <div style={{marginTop: '20px'}}> {filteredProducts.map(product => ( <div key={product.id} style={{padding: '10px', borderBottom: '1px solid #eee'}}> <h4>{product.title}</h4> <p>价格: ${product.price}</p> </div> ))} </div> </div> ); };
你代码里的核心问题
- 状态初始化错误:
searchTerm是输入框的文本值,应该初始化为空字符串"",而非数组[],数组会导致输入框值异常。 - API数据处理错误:目标接口返回的直接是产品数组,不存在
data.Search属性,之前的写法会把状态设为undefined,等于没拿到数据。 - 缺少核心逻辑:没写搜索过滤逻辑,也没把过滤后的结果渲染到页面上,自然看不到效果。
关键逻辑说明
- 过滤逻辑:用
Array.filter()遍历产品列表,把标题和搜索词都转成小写,实现不区分大小写的模糊搜索。 - 列表渲染:用
map()遍历过滤后的数组,用产品的id作为唯一key(React列表渲染要求必须加唯一key),展示标题、价格等信息。 - 实时更新:输入框内容变化时,
searchTerm状态更新,自动触发filteredProducts重新计算,页面随之更新渲染结果。
内容的提问来源于stack exchange,提问作者Ububly
相关产品推荐
相关产品推荐

