React商品名称过滤系统报错:nome.filter is not a function 求解决
问题原因与解决建议
错误根源
报错“nome.filter is not a function”是因为你在handleSearch里把单个商品的name属性(字符串类型)赋值给了nome,然后试图调用数组的filter方法——字符串没有filter方法,自然触发报错。
同时你的逻辑存在其他问题:
- 遍历商品列表时重复重置
nome变量,逻辑混乱 - 用
window.location.reload()重置状态完全没必要,会导致页面刷新丢失当前状态 - 过滤时直接覆盖
filterList的原始数据,导致后续过滤无法恢复完整数据源
修正方案
1. 新增状态存储原始商品数据
需要单独保留从API获取的原始商品列表,避免过滤操作覆盖数据源。添加一个originalList状态:
const [filterList, setFilterList] = useState([]); const [originalList, setOriginalList] = useState([]); // 新增存储原始数据
2. 修正API请求逻辑
获取数据时同时更新原始数据和过滤列表的初始值:
useEffect(() => { fetch('http://127.0.0.1:8000/api/getlist', { method: 'GET' }) .then((res) => res.json()) .then((res) => { setOriginalList(res); // 保存原始数据 setFilterList(res); // 初始化过滤列表 }) .catch(err => console.error('请求失败:', err)); // 不要留空catch,至少打印错误信息 }, []);
3. 重写handleSearch逻辑
直接基于原始数据进行过滤,无需遍历单个商品:
const handleSearch = (event) => { const searchValue = event.target.value.toLowerCase(); if (searchValue === "") { // 清空搜索时恢复原始列表 setFilterList(originalList); } else { // 过滤原始列表,保留名称包含搜索词的商品 const filteredItems = originalList.filter(item => item.name.toLowerCase().includes(searchValue) ); setFilterList(filteredItems); } };
4. 优化加载状态判断
初始filterList是空数组,用原始数据的长度判断加载状态更准确:
if (originalList.length === 0) { return <>Still loading...</>; }
完整修正后代码示例
import { useState, useEffect } from 'react'; function ProductFilter() { const [filterList, setFilterList] = useState([]); const [originalList, setOriginalList] = useState([]); useEffect(() => { fetch('http://127.0.0.1:8000/api/getlist', { method: 'GET' }) .then((res) => res.json()) .then((res) => { setOriginalList(res); setFilterList(res); }) .catch(err => console.error('请求商品列表失败:', err)); }, []); if (originalList.length === 0) { return <>Still loading...</>; } const handleSearch = (event) => { const searchValue = event.target.value.toLowerCase(); if (searchValue === "") { setFilterList(originalList); } else { const filteredItems = originalList.filter(item => item.name.toLowerCase().includes(searchValue) ); setFilterList(filteredItems); } }; return ( <div> <input type="text" onChange={handleSearch} placeholder="搜索商品名称" /> <ul> {filterList.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> </div> ); } export default ProductFilter;
额外说明
如果你的需求是提取所有商品name组成数组后过滤(而非过滤商品对象),可以这样处理:
// 提取所有商品name组成数组 const productNames = originalList.map(item => item.name); // 过滤name数组 const filteredNames = productNames.filter(name => name.toLowerCase().includes(searchValue) );
这种场景下filteredNames是字符串数组,不会出现filter方法报错的问题。
内容的提问来源于stack exchange,提问作者Christian Termo
相关产品推荐
相关产品推荐

