我正在尝试创建一个搜索过滤器,该过滤器将过滤存在于对象数组中的设施名称。如果我将一个数组硬编码为该过滤器可以工作的状态,但我需要它从道具中获取信息。过滤列表正在生成,并在屏幕上显示所有名称,但是当我键入它时,用于过滤的文本框什么也没有发生。我忽略了什么?
class FacilitySearch extends React.Component {
constructor(props) {
super(props);
this.state = {
search: ""
};
}
componentDidMount() {
this.props.dispatch(actions.getFacilitiesList());
}
//The subsr limits the # of characters a user can enter into the seach box
updateSearch = event => {
this.setState({ search: event.target.value.substr(0, 10) });
};
render() {
if (!this.props.facilityList) {
return <div>Loading...</div>
}
let filteredList = this.props.facilityList;
filteredList.filter(facility => {
return facility.facilityName.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1;
});
return (
<div>
<input
type="text"
value={this.state.search}
onChange={this.updateSearch.bind(this)}
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)
答案 0 :(得分:1)
问题是您没有将filter的返回值存储在任何变量中。
您应该执行以下操作:
let filteredList = this.props.facilityList.filter(facility => {
return facility.facilityName.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1;
});
来自MDN: filter()方法创建一个新数组,其中所有通过测试的元素均由提供的函数实现。