React中如何过滤Firestore获取的用户数组并解决map调用报错问题
问题修复方案
核心错误原因
- 你在搜索的onChange回调中,将单个过滤后的用户对象转为字符串后覆盖了
data状态,原本data为数组类型,转为字符串后不存在map方法,因此触发报错。 - 直接修改原始用户列表的状态,过滤后全量原始数据丢失,无法支持多次修改搜索关键词的场景。
- 过滤得到结果数组后无需遍历调用
setData,直接将完整的过滤后数组传入setData即可。
修复步骤
1. 调整状态定义
新增全量原始用户列表和搜索关键词的状态,避免原始数据丢失:
const [data, setData] = useState([]); // 用于渲染的用户列表 const [rawUserList, setRawUserList] = useState([]); // 存储全量原始用户数据 const [searchKey, setSearchKey] = useState(''); // 存储搜索框输入的关键词
2. 修改Firestore数据获取逻辑
获取到数据后同时保存到全量状态和渲染状态:
useEffect(() => { firebase.firestore().collection("Users").get().then((userSnapshot) => { const list = [] userSnapshot.forEach((doc) => { const {powerAccount,first_name,registerDate,email,company,country,phone} = doc.data(); list.push({ usersID: doc.id, powerAccount: powerAccount, first_name: first_name, registerDate: registerDate, email: email, company: company, country: country, phone: phone, }); }); setRawUserList(list); setData(list); // 初始默认展示全量用户 }); },[]);
3. 重写搜索框onChange逻辑
根据输入关键词过滤全量数据,直接将过滤后的完整数组更新到渲染状态:
onChange={(e) => { const keyword = e.target.value.trim(); setSearchKey(keyword); // 搜索关键词为空时恢复展示全量用户 if (!keyword) { setData(rawUserList); return; } // 如需完全匹配可将includes改为=== const filteredList = rawUserList.filter(account => account.powerAccount.includes(keyword)); setData(filteredList); }}
4. 列表渲染逻辑无需修改
修复后data始终为数组类型,可正常调用map方法渲染列表。
内容的提问来源于stack exchange,提问作者motionless570
相关产品推荐
相关产品推荐

