React对象数组搜索过滤器失效问题排查求助
问题分析与解决方案
嘿,这个问题其实挺典型的——你忽略了JavaScript里filter方法的一个关键特性,咱们来一步步搞定它:
核心问题:filter方法不会修改原数组
你当前的代码里,只是调用了filter但完全没用到它返回的结果!filter的设计是返回一个全新的筛选后数组,不会改动原数组。所以你现在的filteredList始终是this.props.facilityList的完整副本,自然输入搜索内容时看不到筛选效果。
问题代码片段:
let filteredList = this.props.facilityList; filteredList.filter(facility => { return facility.facilityName.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1; });
修正后的完整代码
把筛选逻辑改成这样,直接把filter返回的结果赋值给filteredList:
class FacilitySearch extends React.Component { constructor(props) { super(props); this.state = { search: "" }; } componentDidMount() { this.props.dispatch(actions.getFacilitiesList()); } // 限制输入长度的逻辑没问题 updateSearch = event => { this.setState({ search: event.target.value.substr(0, 10) }); }; render() { if (!this.props.facilityList) { return <div>Loading...</div> } // 提前缓存小写的搜索关键词,避免重复计算 const searchKeyword = this.state.search.toLowerCase(); // 直接接收filter返回的筛选后数组 const filteredList = this.props.facilityList.filter(facility => { return facility.facilityName.toLowerCase().includes(searchKeyword); }); return ( <div> {/* 箭头函数已经自动绑定this,不用再手动bind */} <input type="text" value={this.state.search} onChange={this.updateSearch} placeholder="Enter Text Here..." /> <ul> {filteredList.map(facility => { return <li key={facility.generalIdPk}>{facility.facilityName}</li>; })} </ul> </div> ); } } const mapStateToProps = state => ({ facilityList: state.facilityList.facilityList }); export default connect(mapStateToProps)(FacilitySearch)
额外优化小细节
- 用
includes替代indexOf:includes的语义更直观,直接判断字符串是否包含关键词,比indexOf !== -1更易读。 - 去掉多余的
bind:因为updateSearch是箭头函数,它已经自动绑定了组件的this,所以onChange里不需要写this.updateSearch.bind(this)。 - 用
const替代let:filteredList不需要重新赋值,用const更符合代码规范。
这样修改后,你的搜索过滤器就能正常响应输入内容啦!
内容的提问来源于stack exchange,提问作者reactFullStackDeveloper
相关产品推荐
相关产品推荐

