React项目中Firestore来源表格添加搜索栏后结果为空如何解决
问题排查与修复
你代码里共有3处错误导致搜索功能失效:
- 第一,输入事件绑定位置错误:你把
onChange事件绑定到了搜索图标外层的<span>标签上,这个标签本身不会触发输入变化事件,导致searchTerm永远没有被正确赋值,你需要把onChange移到搜索栏的<input>标签上,同时给input加value属性和state绑定,避免可控组件异常。 - 第二,过滤时字段取值路径错误:你从Firestore拉取的用户数据是存在每个数组项的
data属性下的,但你在filter逻辑里直接访问val.email、val.firstname,实际这些字段都在val.data下,访问不存在的属性会得到undefined,调用toLowerCase会导致匹配失败,所有项都被过滤掉。 - 第三,filter函数返回值不规范:filter要求回调返回布尔值,你直接返回val对象虽然不会直接报错,但不符合规范,建议明确返回
true/false。
修正后的关键代码段
1. 搜索栏部分修正
<input type="text" className="form-control" placeholder="Search here" value={this.state.searchTerm} onChange={(e) => this.searchByTerm(e.target.value)} /> {/* 请删掉原span标签上绑定的onChange事件,该事件不会生效 */}
2. 过滤逻辑部分修正
{this.state.Users.filter( val =>{ if (this.state.searchTerm === ""){ return true; } const searchKey = this.state.searchTerm.toLowerCase(); return val.data.email.toLowerCase().includes(searchKey) || val.data.firstname.toLowerCase().includes(searchKey) }).map(data => { // 原有map渲染逻辑保持不变 })}
内容的提问来源于stack exchange,提问作者Houda Boukhobza
相关产品推荐
相关产品推荐

