reactjs - 根据 searchString 和产品大小过滤产品
问题描述
我对 React 还很陌生,还在学习。我正在尝试根据搜索字符串和/或使用基于尺寸状态的过滤器来过滤我的产品概览。
我的搜索是这样进行的:我从输入中获取值并将其插入{this.state.plants.filter
您可以在下面的示例代码底部看到的值。
我的问题是:如何同时按this.state.size
AND过滤产品this.state.searchString
?
或:留空this.state.searchString
,只申请this.state.size
?
我希望我的问题是有道理的。
this.state = {
plants: '',
title: '',
size: '',
searchString: '',
filterSize: ''
};
handleSearch = (event) => {
this.setState({
searchString: event.target.value
})
}
handleSizeFilter = (event) => {
this.setState({
filterSize: event.target.value
})
}
// Search input
<input type="text" className="search" placeholder="Søg" onChange={this.handleSearch} value={this.state.searchString} />
// Size Filter Button
<button onClick={handleSizeFilter} value="22">Size 22</button>
{this.state.plants.filter(plant => plant.title.includes(this.state.searchString)).map(plant => (
{plant.title} - {plant.size}
))}
解决方案
我会在这里做的是:
let filteredPlants = this.state.plants;
const { searchString, filterSize } = this.state;
if (searchString) {
filteredPlants = filteredPlants.filter(plant => plant.title.includes(searchString);
}
if (typeof filterSize === 'number') {
filteredPlants = filteredPlants.filter(plant => plant.size === filterSize);
}
注意:由于这可能是一项昂贵的操作,具体取决于您的数组有多大,最好在类组件中创建一个方法并将其包装在一个实用程序函数中,如memoizeOne。
如果你把它放在你的render
方法中,每次你重新渲染时组件都会遍历数组 - 所以在你的情况下,每次你在输入字段中键入或删除一些东西
推荐阅读
- jquery - 如何使用 Jquery 自动完成来填写表单值
- java - 如何将 .java 重新编译回 .dex
- docker - 如何更改从另一个图像创建的 Dockerfile 中 VOLUME 内文件夹的所有权/权限?
- html - 调整浏览器大小时我的 div 重叠
- python - 如何使用漂亮的汤找到嵌套在元素中的元素?
- python - 从单独的 Python 文件调用方法时出错
- android - 使用注释在 Moshi 中使用嵌套事件序列化 Null
- ruby-on-rails - 运行 Rails 系统测试的 M1 出现分段错误
- javascript - VS 代码扩展“找不到模块 'supports-color'”错误
- xamarin - 如何使用 AVAudioPlayer API 进行同步播放?